Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setTimeout - how to avoid using string for callback?

When using setTimeout, you have to put the code you want to execute into a string:

setTimeout('alert("foobar!");', 1000);

However, I want to execute a function to which I have a reference in a variable. I want to be able to do this:

var myGreatFunction = function() { alert("foobar!"); };
// ...
setTimeout('myGreatFunction();', 1000);

(Though in real life, the alert is a lengthier bit of code and myGreatFunction gets passed around as a parameter to other functions, within which the setTimeout is called.)

Of course, when the timeout triggers, myGreatFunction isn't a recognised function so it doesn't execute.

I wish javascript let me do this, but it doesn't:

setTimeout(function() { myGreatFunction(); }, 1000);

Is there a nice way round this?

like image 294
teedyay Avatar asked Apr 28 '09 09:04

teedyay


People also ask

Does setTimeout use callback?

The setTimeout() function takes two parameters: a callback function and a timeout number in milliseconds. We can make this more obvious by creating a separate function completely instead of using an inline anonymous function. //this is the callback function const timeoutCallback = () => { console.

Does setTimeout block thread?

Explanation: setTimeout() is non-blocking which means it will run when the statements outside of it have executed and then after one second it will execute.

How do I avoid setTimeout?

You can also prevent the setTimeout() method from executing the function by using the clearTimeout() method. If you have multiple setTimeout() methods, then you need to save the IDs returned by each method call and then call clearTimeout() method as many times as needed to clear them all.

What can I use instead of setTimeout?

later.


2 Answers

If you don't need to call myGreatFunction with any arguments, you should be able to pass setTimeout a function reference:

setTimeout(myGreatFunction, 1000);

Also, you should always avoid passing setTimeout code that it needs to evaluate (which is what happens when you wrap the code in quotes). Instead, wrap the code in an anonymous function:

setTimeout(function() {
    // Code here...
}, 1000);

See the setTimeout page at the Mozilla Development Centre for more information.

Steve

like image 170
Steve Harrison Avatar answered Sep 23 '22 05:09

Steve Harrison


Who said that it doesn't let you do it?

It does, the code -

setTimeout(function() { myFunction(); }, 1000);

is perfectly valid.

like image 40
Kirtan Avatar answered Sep 22 '22 05:09

Kirtan