Created
September 20, 2014 08:14
-
-
Save BinaryMuse/19aa812cd2277d8c9555 to your computer and use it in GitHub Desktop.
setTimeout via Web Worker
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
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]; | |
}; |
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
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