Skip to content

Instantly share code, notes, and snippets.

@BinaryMuse
Created September 20, 2014 08:14
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BinaryMuse/19aa812cd2277d8c9555 to your computer and use it in GitHub Desktop.
Save BinaryMuse/19aa812cd2277d8c9555 to your computer and use it in GitHub Desktop.
setTimeout via Web Worker
var timeoutId = 0;
var timeouts = {};
var worker = new Worker("/static/timeout-worker.js");
worker.addEventListener("message", function(evt) {
var data = evt.data,
id = data.id,
fn = timeouts[id].fn,
args = timeouts[id].args;
fn.apply(null, args);
delete timeouts[id];
});
window.setTimeout = function(fn, delay) {
var args = Array.prototype.slice.call(arguments, 2);
timeoutId += 1;
delay = delay || 0;
var id = timeoutId;
timeouts[id] = {fn: fn, args: args};
worker.postMessage({command: "setTimeout", id: id, timeout: delay});
return id;
};
window.clearTimeout = function(id) {
worker.postMessage({command: "clearTimeout", id: id});
delete timeouts[id];
};
var timers = {};
function fireTimeout(id) {
this.postMessage({id: id});
delete timers[id];
}
this.addEventListener("message", function(evt) {
var data = evt.data;
switch (data.command) {
case "setTimeout":
var time = parseInt(data.timeout || 0, 10),
timer = setTimeout(fireTimeout.bind(null, data.id), time);
timers[data.id] = timer;
break;
case "clearTimeout":
var timer = timers[data.id];
if (timer) clearTimeout(timer);
delete timers[data.id];
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment