Skip to content

JavaScript: passing arguments to setTimeout()

JavaScript prides itself on by asynchronous, which I find causes more complications than it solves, as in most cases I need code to execute step by step and not all at the same time. It makes, in my opinion, a lot more sense to have extra complications in the rare cases where I need asynchronous than to have extra complications in the very common cases where I need synchronous.

Among the trivial things that get unnecessarily complicated with asynchronous by default, is pausing. In many programming languages, when you want to pause, it’s just a matter of a trivial line, for instance:
– in PHP: sleep(X)
– in Python: time.sleep(X) (you need to import time for this to work, though)

In JavaScript, you’ll have to refactor your code, putting what you want to delay inside a separate function, and use setTimout(). That is, unless you want to saturate the CPU with an infinite loop for X seconds.

setTimeout() looks simple enough at first:

setTimeout(myDelayedFunction, 1000);

But there is a catch if you want to pass arguments. For instance, this won’t work (arg1 and arg2 will appear to myDelayedFunction as undefined):

    myDelayedFunction(arg1, arg2);
}, 1000);

To passe arguments to the function inside, you’ll have to use this:

setTimeout(function(A, B){
    myDelayedFunction(A, B);
}, 1000, arg1, arg1);

Or also this should work too (not tested)

setTimeout(myDelayedFunction, 1000, arg1, arg1);

Source and other variations there on Stackoverflow

Posted in JavaScript / TypeScript / Node.js, programming.

0 Responses

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.

Some HTML is OK

or, reply to this post via trackback.

Please solve the CAPTCHA below in order to fight spamWordPress CAPTCHA