Skip to content

Instantly share code, notes, and snippets.

@assertchris
Created April 19, 2011 13:51
Show Gist options
  • Save assertchris/927843 to your computer and use it in GitHub Desktop.
Save assertchris/927843 to your computer and use it in GitHub Desktop.
JavaScript unified timeout/interval shim
// Based on the exceptional work of Arian Stolwijk (https://github.com/arian), https://gist.github.com/9286b06108b1dabae4d9
(function(global){
var defaults = {
'setTimeout': global.setTimeout,
'clearTimeout': global.clearTimeout,
'setInterval': global.setInterval,
'clearInterval': global.clearInterval
},
objects = [];
function getTime() {
return +(new Date());
}
function setObject(type, callback, delay) {
var id = objects.length;
objects.push({
'callback': callback,
'time': getTime(),
'delay': delay,
'type': type,
'id': id
});
return id;
}
function clearObject(id) {
var i = objects.length;
while (i--) {
if (objects[i].id == id){
objects.splice(i, 1);
}
}
}
function setTimeout(callback, delay) {
return setObject('timeout', callback, delay);
}
function setInterval(callback, delay) {
return setObject('interval', callback, delay);
}
function clearTimeout(id) {
clearObject.call(global, id);
}
function clearInterval(id) {
clearObject.call(global, id);
}
function tick() {
var time = getTime(),
i = objects.length;
while (i--) {
var object = objects[i];
if (time > object.time + object.delay) {
object.callback();
if (object.type == 'timeout') {
clearObject(object.id);
} else {
object.time = time;
}
}
object = null;
}
i = null;
time = null;
}
defaults.setInterval.call(global, tick, 10);
global.setTimeout = setTimeout;
global.clearTimeout = clearTimeout;
global.setInterval = setInterval;
global.clearInterval = clearInterval;
}(typeof exports != 'undefined' ? exports : window));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment