Uncategorized

differance between setTimeOut and setImmediate with real scenario

Hi friends, after getting to many question what are differance between setTimeOut and setImmediate. when to use setTimeOut and setImmediate. real time example/ scenarion for setTimeOut and setImmediate. now i am trying to explain with simple example, might be helpful for you all.

setTimeout:

setTimeout(,0) essentially means execute after all current functions in the present queue get executed.

setImmediate:

setImmediate is similar in this regard except that it doesn’t use queue of functions. It checks queue of I/O eventhandlers. If all I/O events in the current snapshot are processed, it executes the callback.

Lets explain setImmediate and setImmediate differance with a scenario.

have a look below code.



console.log('GAME LOADING START');
const timeoutScheduled = Date.now();
// If game not loaded in 3 sec show message. 
let timeOutAfter3Sec = setTimeout(() => {
    console.log("it seems like you are offline check your internet connectivity/ might be compatiblity issue.");
clearImmediate(allisGood);
}, 3000); // After checking compatibility and internet connectivity, if everythings fine show this message. let allisGood=setImmediate(() => { console.log('Everythings are fine enjoy game'); }); // Code to check internet connectivity and compatibility. let doCheck = function () { // Check start, you can change 1.5e10 value to simulate both scenaion. set less value to call allisGood and more for timeOutAfter3Sec for (var i = 0; i < 1.5e2; i++) { //checking } // Check end //Now calculate delay time, //if less than 3 sec(2900ms), clearTimeOut For showing offline/compatibility, in this case setImmediate will call and display message //if more than 3 sec(2900ms), setTimeOut will fire from event loop que, and will clear clearImmediate. const delay = Date.now() - timeoutScheduled; if (delay < 2900) { clearTimeout(timeOutAfter3Sec); } console.log('loop end time',Date.now(),'delay',delay); } // call check function. doCheck();

i hope this line of code helpful for you, if enjoyed please share on social channel might be helpful for other. if have any doubt can ask/comment.

Submit your review
1
2
3
4
5
Submit
     
Cancel

Create your own review

Community
Average rating:  
 1 reviews
by Tanmay Tomar on Community
Nice blog, very useful for beginner

Nice blog, very useful for beginner