使用jQuery的与settimeout推迟 [英] using jquery's deferred with settimeout
问题描述
我有一个带有内部循环的模块(使用'settimeout').我想在每次计时器发生时触发回调.我没有运气就尝试使用jQuery的延迟对象..
I have a module that has an internal loop (using 'settimeout'). I want to fire a callback each time the timer happens. I tried using jQuery's deferred object with no luck.. Something like:
$(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);".主程序.我可以使用老式的函数回调(将回调函数传递给模块),但我真的想尝试这些出色的功能.
The problem is that the timer calls the method internally, so I will not have a call to ".then(Do Something);" of the main program. I can use the old school function callback (pass a callback function to the module) but I really wanted to try these great feature.
谢谢
Yaniv
推荐答案
延迟实际上不是您想要的,因为那是一次性交易-您可能想要的是回调列表.
A deferred really isn't what you're looking for because that's a one time deal - what you likely want is a Callback list.
jQuery以$ .Callbacks()的形式提供了它,这可能正是您想要的.
jQuery provides that as $.Callbacks() which might be what you're looking for.
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/
JSFiddle: http://jsfiddle.net/SUsyj/
这篇关于使用jQuery的与settimeout推迟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!