Skip to content

Instantly share code, notes, and snippets.

@fhdalikhan
Last active April 23, 2019 08:03
Show Gist options
  • Save fhdalikhan/12e06ff7cde5a43a2b8b241481d9fc0c to your computer and use it in GitHub Desktop.
Save fhdalikhan/12e06ff7cde5a43a2b8b241481d9fc0c to your computer and use it in GitHub Desktop.
Javascript single threaded nature examples below.
// output is 1,3,2
console.log('1');
window.setTimeout(function(){
console.log('2');
}, 0);
console.log('3');
// because javascript is single threaded, i.e. a block of code is executed in a single thread.
// setTimeout and setInterval are special because they are executed in another thread.
// setTimeout and setInterval send the code to the end of the event bus, they are executed in last.
// so lets take this example, when we have a blocking code like a while loop after setTimeout / setInterval,
// the code of setTimeout / setInterval will execute after the blocking code, for e.g. while loop here.
// also check out this nice article from john resig https://johnresig.com/blog/how-javascript-timers-work/
(function () {
var startTime = new Date().getTime();
console.log('setting timeout 0 callback at ' +sinceStart());
setTimeout(function(){
console.log('in timeout callback at ' +sinceStart())
}, 0);
console.log('starting blocking loop at ' +sinceStart());
while (sinceStart() < 3000) {
continue;
}
console.log('blocking loop ended at ' +sinceStart());
return;
function sinceStart () {
return new Date().getTime() - startTime
}
}());
// output is setting
// timeout 0 callback at 1 debugger eval code:5:3
// starting blocking loop at 1 debugger eval code:11:3
// blocking loop ended at 3000 debugger eval code:17:3
// undefined
// in timeout callback at 3001
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment