如何在Coffeescript中使用setTimeout()

时间:2013-10-29 16:52:46

标签: coffeescript

我似乎无法使用setTimeout()来调用我自己的函数之一。我可以使用setTimeout来调用alert(),但不能使用我自己编写的函数。这是重现问题的最简单的代码:

我有以下coffeeScript

    setTimeout(run, 1000)

    run = () ->
        console.log("run was called!")

生成以下Javascript

    // Generated by CoffeeScript 1.6.3
    (function() {
      var run;

      setTimeout(run, 1000);

      run = function() {
        return console.log("run was called!");
      };

    }).call(this);

没有任何内容打印到控制台。

2 个答案:

答案 0 :(得分:23)

run = () ->
    console.log("run was called!")
setTimeout(run, 1000)

对于使用语法function run(){}声明的函数,您依赖javascript function hoisting,但coffeescript将它们声明为变量:var run = function(){},因此您必须在引用之前定义函数,否则当您将其传递给undefined时,它仍然是setTimeout

答案 1 :(得分:16)

匿名选项:

彼得是完全正确的。但您也可以在不声明变量的情况下使用setTimeout

setTimeout ->
    console.log 'run was called!'
, 1000

收率:

(function() {
    setTimeout(function() {
        return console.log("run was called!")
    }, 1e3)
}).call(this);