Mik*_*epo 4 javascript timer callback
我想在javascript中创建一个全局计时器对象,然后能够动态添加回调.这样我就可以在我的脚本中使用一个全局计时器以一定的间隔执行所有操作,而不是通过使用倍数来浪费资源.
这就是我希望能够将事物拼凑在一起的方式:
var timer = new function() {
clearInterval( this.interval );
//[1] At this point I want the Callbacks to be run
var self = this;
setTimeout(function() {self.timer()}, 200);
}
function otherObject = new function() {
//When created I want to bind my object's function called cb to the global timer at [1]
}
otherObject.prototype.cb = function() {
//Stuff that should be done every time the timer is run
}
var someObject = new otherObject();
Run Code Online (Sandbox Code Playgroud)
我怎样才能将任何数字函数(大多数是其他对象中的函数)绑定到我的计时器间隔运行?
小智 6
创建一个GlobalTimer对象,使其能够注册回调函数并取消自身.
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);
Run Code Online (Sandbox Code Playgroud)