Created
July 23, 2015 00:02
-
-
Save voltrevo/3493e096de9fe57c26d5 to your computer and use it in GitHub Desktop.
Alternative to setInterval / clearInterval
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 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