Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use setTimeout() in Coffeescript

Tags:

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.

like image 573
rafaelcosman Avatar asked Oct 29 '13 16:10

rafaelcosman


People also ask

Why is the setTimeout () function used?

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.

What is the use of setTimeout () in JavaScript?

setTimeout() The global setTimeout() method sets a timer which executes a function or specified piece of code once the timer expires.

How does a setTimeout work?

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.

What is the use of setTimeout in typescript?

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.


1 Answers

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.

like image 97
Peter Lyons Avatar answered Oct 12 '22 01:10

Peter Lyons