8

I tried to understand of how deferred works,so in all of them they use setTimeout.

this.callbacks;// array of functions reference
this.callbacks.forEach(function(callback){
    window.setTimeout(function(){
          callback(data);
    },0);
});

one example from this questions that use setTimeout

resolve: function (data) {
    this.promise.okCallbacks.forEach(function(callback) {
      window.setTimeout(function () {
        callback(data)
      }, 0);
    });
  },

What is the different between calling functions in loop by setTimeout than callback(); or callback.call();

Community
  • 1
  • 1
Moein Hosseini
  • 4,309
  • 15
  • 68
  • 106

4 Answers4

13

The reason for doing this is to allow the javascript thread an opportunity to trigger any other events that may be waiting in the queue.

Javascript is single-threaded. If an event is triggered, it can only run when the currently running code has finished.

Using setTimeout with a zero time delay effectively tells the JS interpreter that the callback function call is part of a new context and that your current code block is finished. This means that JS will take the opportunity before calling callback() to check to see if any other events need to be handled.

Although this may delay callback() itself from being called immediately, this can be good for your site's overall performance:

Other events that may need to be handled include click events and other UI triggers. If you don't give them a chance to execute, it may make your user interface appear sluggish or non-responsive.

Spudley
  • 166,037
  • 39
  • 233
  • 307
2

setTimeout runs after the time has elapsed and the JavaScript process is free.

Using call would run the callback immediately and block everything else.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • @Moein7tl: Actually there is a lower bound to the timeout, which is greater than 0 (IIRC it's something like 4 msec for popular browsers). Hence 0 means "as soon as you can get round to it". Presumably people who use a zero timeout know about this and do it on purpose. – Jon Aug 29 '13 at 11:24
  • 1
    @Moein7tl — Yes, note that after I said "time has elapsed" I said **"and"**. – Quentin Aug 29 '13 at 11:36
2

setTimeout(func,0) is not called immediately.

Simply it simulate an asynchronous function with a callback.

function asyncFunc(callback) {
    console.log("step1");
    setTimeout(callback,0);
    console.log("step2");
}

asyncFunc(function() {console.log("async step")});
/* output:
step1
step2
async step
*/

https://developer.mozilla.org/en-US/docs/Web/API/window.setTimeout

Code executed by setTimeout() is run in a separate execution context to the function from which it was called

So it runs in a separate execution context, but before execute it, javascript should end the current execution due javascript running on single-thread.

It doesn't matter how much time during current execution, because it MUST end before execute another task.

if you have a infinite loop before the end of task, for example, your callback never be called.

Luca Rainone
  • 16,138
  • 2
  • 38
  • 52
1

setTimeout() allow you to register a function to be invoked once after a specified amount of time has elapsed.

The setTimeout() method of the Window object schedules a function to run after a specified number of milliseconds elapses. setTimeout() returns a value that can be passed to clearTimeout() to cancel the execution of the scheduled function.

If you call setTimeout() with a time of 0 ms, the function you specify is not invoked right away. Instead, it is placed on a queue to be invoked “as soon as possible” after any currently pending event handlers finish running.

Moazzam Khan
  • 3,130
  • 2
  • 20
  • 35