我有一个具有内部循环的模块(使用“settimeout”)。我想在每次计时器发生时触发回调。我尝试使用 jQuery 的延迟对象,但没有成功。类似于:
$(function(){
var module = new MyModule();
$.when(module.init()).then("DO Something");
});
function MyModule(){
this.d = $.Deferred();
}
test.prototype.init = function(){
clearTimeout(this.next);
var self = this;
/* Do Something */
self.d.resolve();
this.next = setTimeout(function(){
self.init(); /* The problem is here - internal call to self */
}, 4000);
return self.d.promise();
};
问题是计时器在内部调用该方法,因此我不会调用“.then(Do Something);”主程序的。我可以使用老式函数回调(将回调函数传递给模块),但我真的很想尝试这些很棒的功能。
谢谢
亚尼夫
最佳答案
延迟确实不是您想要的,因为这是一次性交易 - 您可能需要的是回调列表。
jQuery 将其作为 $.Callbacks() 提供,这可能就是您正在寻找的内容。
function MyModule(){
this._initCallbacks = $.Callbacks();
}
MyModule.prototype.onInit = function( cb ) {
if ( typeof cb === "function" ) {
this._initCallbacks.add( cb );
}
};
MyModule.prototype.init = function(){
clearTimeout( this.next );
var self = this;
this._callbacks.fire();
this.next = setTimeout(function(){
self.init();
}, 4000);
return this;
};
$(function(){
var module = new MyModule();
module.onInit(function() {
console.log( "Do something" );
});
module.init();
});
JSFiddle:http://jsfiddle.net/SUsyj/
关于javascript - 使用 jquery 的 deferred 和 settimeout,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12537939/