Reputation: 2599
I can't seem to use setTimeout() to call one of my own functions. I can use setTimeout to call alert(), but not a function that I've written myself. Here's the simplest code that reproduces the problem:
I have the following coffeeScript
setTimeout(run, 1000)
run = () ->
console.log("run was called!")
Which generates the following Javascript
// Generated by CoffeeScript 1.6.3
(function() {
var run;
setTimeout(run, 1000);
run = function() {
return console.log("run was called!");
};
}).call(this);
Nothing is printed to the console.
Upvotes: 26
Views: 22353
Reputation: 54856
Peter is exactly right. But you can also use setTimeout
without declaring a variable:
setTimeout ->
console.log 'run was called!'
, 1000
Yields:
(function() {
setTimeout(function() {
return console.log("run was called!")
}, 1e3)
}).call(this);
Upvotes: 23
Reputation: 146174
run = () ->
console.log("run was called!")
setTimeout(run, 1000)
You are relying on javascript function hoisting for functions declared with the syntax function run(){}
, but coffeescript declares them as variables: var run = function(){}
, so you have to define the function before you reference it, otherwise it's still undefined
when you pass it to setTimeout
.
Upvotes: 27