Skip to content

Instantly share code, notes, and snippets.

@liamgriffiths
Created November 7, 2014 04:24
Show Gist options
  • Save liamgriffiths/1c29ebb84e5225b98345 to your computer and use it in GitHub Desktop.
Save liamgriffiths/1c29ebb84e5225b98345 to your computer and use it in GitHub Desktop.
timers in javascript/node.js
/**
* timers in action
* http://nodejs.org/api/timers.html
*/
// lastly this one is called, because it isn't resolved on the queue until ~50ms
// long after all the other functions are queued up in the event loop
setTimeout(function() {
console.log(5);
}, 50);
// `setImmediate` functions are queued up "...after I/O events callbacks and
// before setTimeout and setInterval..." but oddly, this doesn't seem to be the
// case. see `setTimeout(fn, 10)`
setImmediate(function() {
console.log(4);
});
// `setTimeout` with 10ms isn't much more than 0ms, but it is triggered before
// `setImmediate`... not sure why
setTimeout(function() {
console.log(3.5);
}, 10);
// after the `nextTick` callback is executed, the call stack is empty again, so
// the async tasks start to pushed on to the call stack, 0 being the first to
// run
setTimeout(function() {
console.log(3);
}, 0);
// since the call stack is empty, and the `setTimeouts` && `setImmediate` and
// queued up, `nextTick` runs at the start of the next event loop cycle
process.nextTick(function() {
console.log(2);
});
// first function on the call stack - runs first
console.log(1);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment