Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use setTimeout in deferred

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();

like image 573
Moein Hosseini Avatar asked Aug 29 '13 11:08

Moein Hosseini


People also ask

Why do you need setTimeout?

The setTimeout() function registers the function provided as a parameter to be executed after some provided(3000) milliseconds. The browser keeps a record of it internally and as soon as the timer expires, it enqueues that function to the callback queue.

Does setTimeout affect performance?

No significant effect at all, setTimeout runs in an event loop, it doesn't block or harm execution.

Is setTimeout a good practice?

Most of the time, we use “setTimeout()” to let some code run a certain period of time. However, it can cause problems when it is not used not carefully.

Should I use setInterval or setTimeout?

Usage notes. The setInterval() function is commonly used to set a delay for functions that are executed again and again, such as animations. You can cancel the interval using clearInterval() . If you wish to have your function called once after the specified delay, use setTimeout() .


2 Answers

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.

like image 60
Spudley Avatar answered Sep 23 '22 18:09

Spudley


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

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

like image 31
Quentin Avatar answered Sep 20 '22 18:09

Quentin