如何在Coffeescript中使用setTimeout()

如何在Coffeescript中使用setTimeout(),coffeescript,Coffeescript,我似乎无法使用setTimeout()调用我自己的函数之一。我可以使用setTimeout调用alert(),但不是我自己编写的函数。下面是重现问题的最简单代码: 我有下面的咖啡脚本 setTimeout(run, 1000) run = () -> console.log("run was called!") 这将生成以下Javascript // Generated by CoffeeScript 1.6.3 (function()

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

我有下面的咖啡脚本

    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);
控制台上没有打印任何内容

run = () ->
    console.log("run was called!")
setTimeout(run, 1000)
您依赖于使用语法
function run(){}
声明的函数,但coffeescript将它们声明为变量:
var run=function(){}
,因此您必须在引用函数之前定义它,否则当您将其传递到
setTimeout
匿名选项时,它仍然是
未定义的
: 彼得完全正确。但您也可以使用
setTimeout
,而无需声明变量:

setTimeout ->
    console.log 'run was called!'
, 1000
收益率:

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

我不知道coffeescript,但它看起来像是您试图调用一个函数,您应该只在其中传递参数/etc.
setTimeout(()=>{//Some code},1000)垃圾收集怎么样?一次性可能?这个答案的关键是,在coffeescript中,
console.log
语句前面有4个空格。如果只有两个空格,它将无法工作。在Coffeescript中,每个制表符或2个空格缩进一个级别。在一行:
setTimeout((->someFunction()),1000)