Skip to content

Instantly share code, notes, and snippets.

@yefremov
Last active March 13, 2017 20:55
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 yefremov/26b7c1c194f59418104ed7b2acf14e08 to your computer and use it in GitHub Desktop.
Save yefremov/26b7c1c194f59418104ed7b2acf14e08 to your computer and use it in GitHub Desktop.
Simple browser version of nextTick function
// 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