Skip to content

Instantly share code, notes, and snippets.

@mushtat
Created April 25, 2016 08:38
Show Gist options
  • Save mushtat/e2b787e595c178fc920d8734d698fa61 to your computer and use it in GitHub Desktop.
Save mushtat/e2b787e595c178fc920d8734d698fa61 to your computer and use it in GitHub Desktop.
Worker-timer
function factory(root){
if (root === root.window && root.URL && root.Blob && root.Worker) {
return (function() {
var TIMER_WORKER_SOURCE = [
"var timerIds = {}, _ = {};",
"_.setInterval = function(args) {",
" timerIds[args.timerId] = setInterval(function() { postMessage(args.timerId); }, args.delay);",
"};",
"_.clearInterval = function(args) {",
" clearInterval(timerIds[args.timerId]);",
"};",
"_.setTimeout = function(args) {",
" timerIds[args.timerId] = setTimeout(function() { postMessage(args.timerId); }, args.delay);",
"};",
"_.clearTimeout = function(args) {",
" clearTimeout(timerIds[args.timerId]);",
"};",
"onmessage = function(e) { _[e.data.type](e.data) };"
].join("");
var _timerId = 0;
var _callbacks = {};
var _timer = new root.Worker(root.URL.createObjectURL(
new root.Blob([ TIMER_WORKER_SOURCE ], { type: "text/javascript" })
));
_timer.onmessage = function(e) {
if (_callbacks[e.data]) {
_callbacks[e.data].callback.apply(null, _callbacks[e.data].params);
}
};
return {
setInterval: function(callback, delay) {
var params = Array.prototype.slice.call(arguments, 2);
_timerId += 1;
_timer.postMessage({ type: "setInterval", timerId: _timerId, delay: delay });
_callbacks[_timerId] = { callback: callback, params: params };
return _timerId;
},
setTimeout: function(callback, delay) {
var params = Array.prototype.slice.call(arguments, 2);
_timerId += 1;
_timer.postMessage({ type: "setTimeout", timerId: _timerId, delay: delay });
_callbacks[_timerId] = { callback: callback, params: params };
return _timerId;
},
clearInterval: function(timerId) {
_timer.postMessage({ type: "clearInterval", timerId: timerId });
_callbacks[timerId] = null;
},
clearTimeout: function(timerId) {
_timer.postMessage({ type: "clearTimeout", timerId: timerId });
_callbacks[timerId] = null;
}
};
})();
} else {
return root;
}
}
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(factory.bind(this, this));
} else if (typeof module === 'object' && module.exports) {
// Node. Does not work with strict CommonJS, but
// only CommonJS-like environments that support module.exports,
// like Node.
module.exports = factory(this);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment