Skip to content

Instantly share code, notes, and snippets.

@chidumennamdi
Created September 11, 2018 19:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chidumennamdi/de4bf5746cd02754c9edb6078da5212a to your computer and use it in GitHub Desktop.
Save chidumennamdi/de4bf5746cd02754c9edb6078da5212a to your computer and use it in GitHub Desktop.
// time.js
let loop = {
time: Date.now(),
timer_heap: [],
enqueue: function(timer) {
this.timer_heap.push(timer)
this.timer_heap.sort((a, b) => a.ms - b.ms)
},
dequeue: function() {
this.timer_heap.splice(0, 1);
},
min: function() {
if (this.timer_heap.length != 0) {
return this.timer_heap[0]
}
return null
}
}
function uv_timer_stop() {
loop.dequeue()
}
function uv_update_time () {
loop.time = Date.now()
}
function uv_run_timers() {
let timer
for (;;) {
timer = loop.min()
if (timer == null)
break;
if (timer.ms > loop.time)
break;
uv_timer_stop()
timer.cb()
}
}
function uv_loop_alive() {
return loop.timer_heap.length == 0 ? 0 : 1
}
function uv_run() {
let r
while (r != 0) {
uv_update_time()
uv_run_timers()
r = uv_loop_alive()
}
}
global.setTimeout = function setTimeout(cb, ms) {
loop.enqueue({ cb, ms: ms + loop.time })
}
setTimeout(() => console.log('60ms Timeout'), 60)
setTimeout(() => console.log('0ms Timeout'), 0)
setTimeout(() => console.log('1ms Timeout'), 1)
setTimeout(() => console.log('400ms Timeout'), 400)
uv_run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment