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.
Note: The setTimeout() method is useful when you want to execute a block of once after some time. For example, showing a message to a user after the specified time.
setTimeout() The global setTimeout() method sets a timer which executes a function or specified piece of code once the timer expires.
The setTimeout() sets a timer and executes a callback function after the timer expires. In this syntax: cb is a callback function to be executed after the timer expires. delay is the time in milliseconds that the timer should wait before executing the callback function.
setTimeout() is a method used to call a function after a specified amount of time in milliseconds. This method acts as a timer and executes the code after the timer expires. setTimeout() cannot be executed multiple times; it can only be executed once.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With