Created
July 9, 2013 16:49
-
-
Save nikcorg/5959044 to your computer and use it in GitHub Desktop.
A naive and simple experiment at setImmediate/clearImmediate polyfilling
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
(function (global, rand) { | |
var prefix = "setImmediate-"; | |
var counter = 0; | |
var tasks = {}; | |
global.setImmediate = function (cb, params) { | |
var id = prefix + counter++ + rand(); | |
tasks[id] = { | |
fn: cb, p: params || [] | |
}; | |
window.postMessage(id, "*"); | |
}; | |
global.clearImmediate = function (cb) { | |
Object.keys(tasks).some(function (key) { | |
var task = tasks[key]; | |
if (task && task.fn === cb) { | |
delete tasks[key]; | |
return true; | |
} | |
return false; | |
}); | |
}; | |
runTask = function (e) { | |
var task; | |
if (! e.data.substr(0, prefix.length) === prefix) { | |
return; | |
} | |
task = tasks[e.data]; | |
if (! task || typeof task.fn !== "function") { | |
return; | |
} | |
task.fn.apply(global, task.p); | |
delete tasks[key]; | |
}; | |
global.addEventListener("message", runTask, false); | |
}(window, Math.random)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
On MS's demo for the setImmediate API copy and paste the following snippet to your console, then run the
setImmediate
version of quicksort