Skip to content

Instantly share code, notes, and snippets.

@voltrevo
Created July 23, 2015 00:02
Show Gist options
  • Save voltrevo/3493e096de9fe57c26d5 to your computer and use it in GitHub Desktop.
Save voltrevo/3493e096de9fe57c26d5 to your computer and use it in GitHub Desktop.
Alternative to setInterval / clearInterval
var interval = (function() {
var api = {};
var idMap = {};
var nextId = 0;
api.set = function(task, ms) {
var nextTime = Date.now() + ms;
var id = nextId++;
var trigger = function() {
task();
nextTime += ms;
idMap[id] = setTimeout(trigger, nextTime - Date.now());
};
idMap[id] = setTimeout(trigger, nextTime - Date.now());
return id;
};
api.clear = function(id) {
clearTimeout(idMap[id]);
delete idMap[id];
};
return api;
})();
var blockSync = function(ms) {
var start = Date.now();
while (Date.now() - start < ms);
};
var nativeDemo = function() {
var start = Date.now();
var id = setInterval(function() {
console.log(((Date.now() - start) / 1000).toFixed(3));
blockSync(500);
}, 1000);
setTimeout(function() {
clearInterval(id);
}, 10000);
};
var altDemo = function() {
var start = Date.now();
var id = interval.set(function() {
console.log(((Date.now() - start) / 1000).toFixed(3));
blockSync(500);
}, 1000);
setTimeout(function() {
interval.clear(id);
}, 10000);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment