Skip to content

Instantly share code, notes, and snippets.

@ankur-anand
Created September 9, 2017 10:04
Show Gist options
  • Save ankur-anand/3376e6057f35773f11ce3c332bc4d3ee to your computer and use it in GitHub Desktop.
Save ankur-anand/3376e6057f35773f11ce3c332bc4d3ee to your computer and use it in GitHub Desktop.
Non-deterministic order of execution of setTimeout vs setImmediate in node.js event-loop
setTimeout(function timeout () {
 console.log(‘timeout’);
},0);
setImmediate(function immediate () {
 console.log(‘immediate’);
});
$ node timeout_vs_immediate.js
timeout
immediate
$ node timeout_vs_immediate.js
immediate
timeout
int uv_run(uv_loop_t* loop, uv_run_mode mode) {
 int timeout;
 int r;
 int ran_pending;
 r = uv__loop_alive(loop);
 if (!r)
 uv__update_time(loop);
 while (r != 0 && loop->stop_flag == 0) {
 uv__update_time(loop);
 uv__run_timers(loop);
 ran_pending = uv__run_pending(loop);
 uv__run_idle(loop);
 uv__run_prepare(loop);
 ……
 uv__io_poll(loop, timeout);
 uv__run_check(loop);
 uv__run_closing_handles(loop);
 …………
void uv_update_time(uv_loop_t* loop) {
 uv__update_time(loop);
}
UV_UNUSED(static void uv__update_time(uv_loop_t* loop)) {
 
 */
 loop->time = uv__hrtime(UV_CLOCK_FAST) / 1000000;
}
uint64_t uv__hrtime(uv_clocktype_t type) {
 struct timespec ts;
 clock_gettime(CLOCK_MONOTONIC, &ts);
 return (((uint64_t) ts.tv_sec) * NANOSEC + ts.tv_nsec);
}
void uv__run_timers(uv_loop_t* loop) {
 …
 for (;;) {
 ….
 handle = container_of(heap_node, uv_timer_t, heap_node);
 if (handle->timeout > loop->time)
 break;
 ….
 uv_timer_again(handle);
 handle->timer_cb(handle);
 }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment