Last active
March 13, 2017 20:55
-
-
Save yefremov/26b7c1c194f59418104ed7b2acf14e08 to your computer and use it in GitHub Desktop.
Simple browser version of nextTick function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// https://github.com/kriskowal/q/blob/d373079d3620152e3d60e82f27265a09ee0e81bd/q.js#L101-L248 | |
// Use the fastest possible means to execute a task in a future turn | |
// of the event loop. | |
var nextTick = (function () { | |
var head = {task: null, tail: null}; | |
var tail = head; | |
var flushing = false; | |
function run(task) { | |
try { | |
task(); | |
} catch (e) { | |
setTimeout(function () { | |
throw e; | |
}, 0); | |
} | |
} | |
function flush() { | |
var task; | |
while (head.next) { | |
head = head.next; | |
task = head.task; | |
head.task = null; | |
run(task); | |
} | |
flushing = false; | |
} | |
nextTick = function (task) { | |
tail = tail.next = { | |
task: task, | |
next: null | |
}; | |
if (!flushing) { | |
flushing = true; | |
setTimeout(flush, 0); | |
} | |
}; | |
return nextTick; | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment