I want to create a global timer object in javascript and then be able to add callbacks to it on the fly. This way I can just use one global timer in my script to execute all
Create a GlobalTimer object and give it the ability to register callback functions and cancel itself.
function makeGlobalTimer(freq) {
freq = freq || 1000;
// array of callback functions
var callbacks = [];
// register the global timer
var id = setInterval(
function() {
var idx;
for (idx in callbacks) {
callbacks[idx]();
}
}, freq);
// return a Global Timer object
return {
"id": function() { return id; },
"registerCallback": function(cb) {
callbacks.push(cb);
},
"cancel": function() {
if (id !== null) {
clearInterval(id);
id = null;
}
}
};
}
var gt = makeGlobalTimer(500);
gt.registerCallback(function() {
console.log("a");
});
gt.registerCallback(function() {
console.log("b");
});
setTimeout(function() { gt.cancel(); }, 5000);