Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save amitguptagwl/4c065526ed17ea9ce5b5609b7a2ab9cf to your computer and use it in GitHub Desktop.
Save amitguptagwl/4c065526ed17ea9ce5b5609b7a2ab9cf to your computer and use it in GitHub Desktop.
const util = require('util');
const process = require('process');
const sleep = util.promisify(setTimeout);
var a = function(callback){
callback();
}
a(async function(){
console.log("print me first");
await sleep(2000);
console.log("print me in last");
})
//queue callback for execution after given duration
//so the given callback will be executed after all functions and event handlers already queued at that time.
setTimeout( function(){
console.log("print me after 2000 ms");
},2000)
//after currently executing I/O call back
//similar to setTimeout(callback,0) but it doesn't check queue of functions but only the queue of I/O eventhandlers
//Use setImmediate if you want to queue the function behind whatever I/O event callbacks that are already in the event queue.
setImmediate( function(){
console.log("then me on 3rd priority");
})
const timeid= setInterval(function(){
console.log("then me on 2nd priority");
clearInterval(timeid);
}, 0);
//execute given callback once all the queued functions and event handlers are executed
setTimeout( function(){
console.log("then me on 2nd priority too");
},0)
//Use process.nextTick to effectively queue the function at the head of the event queue so that it executes immediately after the current function completes.
process.nextTick( function(){//blocking
console.log("then me on 1st priority");
})
//So in a case where you're trying to break up a long running, CPU-bound job using recursion, you would now want to use setImmediate rather than process.nextTick to queue the next iteration as otherwise any I/O event callbacks wouldn't get the chance to run between iterations.
a(async function(){
console.log("print me first too");
await sleep(2000);
console.log("print me in last too");
})
console.log("print me 2nd");
/* Output
print me first
print me first too
print me 2nd
then me on 1st priority
then me on 2nd priority
then me on 2nd priority too
then me on 3rd priority
print me after 2000 ms
print me in last
print me in last too
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment