7

Why do we need to pass a function to Javascript setTimeOut https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers.setTimeout

Why cannot we do sg simple like

setTimeOut(1000);

Can I pass an empty or nonexistant function in there?

I want to simply wait in a for loop after each iteration.

giorgio79
  • 3,025
  • 7
  • 42
  • 70

4 Answers4

14

Javascript is single threaded. You can use setTimemout to postpone an operation, but the thread will continue. So

function some() {
  doStuff();
  setTimeout(otherStuff, 1000);
  doMoreStuff();
}

will run doStuff and doMoreStuff subsequently, and will run otherStuff after a second. That's why it's useless and impossible to use setTimeout as a delay per se. If doMoreStuff should be postponed, you should make that the callback for the delay:

function some() {
  doStuff();
  setTimeout(doMoreStuff, 1000);
}

or both otherstuff and doMoreStuff delayed:

function some() {
  doStuff();
  setTimeout(function () {
               otherStuff();
               doMoreStuff()
             }, 1000);
}

Maybe my answer to this SO-question is usefull too.

Community
  • 1
  • 1
KooiInc
  • 104,388
  • 28
  • 131
  • 164
  • @Kooilnc How are all these solutions good in this post?: [Post](http://stackoverflow.com/questions/5226285/settimeout-in-a-for-loop-and-pass-i-as-value). You posted a nice solution but the solutions in the link only work with two iterations. With more than two iterations it just continues firing and gives you back random numbers. Was there a change in how browsers handle timeouts in loops over the last years? – Michelangelo Feb 09 '15 at 10:32
  • @Mikey: check the answer to the question I linked, and checked the jsfiddle in that answer (http://jsfiddle.net/KooiInc/k47rw5o4/) – KooiInc Feb 09 '15 at 10:57
  • Thanks. Explains a lot. – Michelangelo Feb 09 '15 at 11:02
3

setTimeout registers an even in the event loop. When JavaScript has finished all it's current instructions, it returns to the event loop and waits for an event to happen. When it does, it invokes the callback function, which is the function you pass to setTimeout.

To do a for-loop with setTimeout, do something like this:

function loop(i, n) {
    doStuff();
    if (i < n) {
        setTimeout(function() {
            loop(i+1, n);
        }, 1000);
    }
};
loop(0, 10);

where i is the current iteration and n is max iterations

When JavaScript is not in the event loop, i.e. it's running code, it makes the whole browser unresponsive. Just idling for a second would do exactly this, so if you iterate 10 times over a loop, the browser would be unresponsive for 10 seconds

Suppen
  • 776
  • 1
  • 6
  • 18
1

--> setTimeout(callbackFunction[, interval])

This can be understand as you are going to call a function with the specified name(Given by you) after an specified time.

--> You cannot do like this setTimeOut(1000); because 1000 will be treated as callback function As the first parameter of setTimeout() is callback function.

You cannot define a function like

function 1000() { // Code Resides here. }

because java script does not allow these type of function names.

--> You can pass anonymous function to setTimeout() like

setTimeout(function() { // Code resides here. }[, interval]); The above function code will be executed after the given interval. If no interval is given then it will executed immediately.

Note:- Parameters given in square brackets ([, ]) are optional to pass.

--> You can refer the below mentioned thread for your use: JavaScript sleep/wait before continuing

As this thread contains a function definition which works like sleep() in other languages.

Community
  • 1
  • 1
Jitendra Khatri
  • 734
  • 3
  • 15
1

This is now possible with Await/Async in a quick one line:

await new Promise(resolve => setTimeout(resolve, 1000));

There is another question I think is relevant at Combination of async function + await + setTimeout