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();
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.
No significant effect at all, setTimeout runs in an event loop, it doesn't block or harm execution.
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.
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() .
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.
setTimeout
runs after the time has elapsed and the JavaScript process is free.
Using call
would run the callback immediately and block everything else.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With