Just a slightly modified version of the aekeus approach. Now with pauses and renewable timers, the third arguments and faster callbacks -loop:
function Interval(callback, freq) { // array of callback functions var args = arguments, callbacks = [callback], paused = false; // register the global timer var id = setInterval(function () { if(paused) return; var len = callbacks.length, i = len; while(i--) callbacks[len - 1 - i].apply(Interval, Array.prototype.slice.call(args, 2, args.length)); }, freq); // return a Global Timer object return { id: function () { return id; }, add: function (cb) { callbacks.push(cb); }, clear: function () { if (id === null) return; clearInterval(id); id = null; }, pause: function(){ paused = true; }, resume: function(){ paused = false; } }; }
You can pass extra arguments as the default setInterval (even in IE lt 9):
function callback(date) { console.log(date); } var interval = Interval(callback, 1000, new Date);
Usage example:
var interval = Interval(function () { console.log("init", new Date); }, 1000); interval.add(function () { console.log("a", new Date); }); interval.add(function () { console.log("b", new Date); }); document.onmousedown = interval.pause; document.onmouseup = interval.resume;
source share