javascript - 使用 jquery 的 deferred 和 settimeout

标签 javascript jquery jquery-deferred deferred

我有一个具有内部循环的模块(使用“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/

相关文章:

jquery选择器: how can I use JQuery to select the child of a parent?

javascript - JS 在多个 .load() 函数完成后继续

javascript - 使用 ASYNC AJAX 调用处理 Deferrred

如果在离线时加载/刷新页面,JavaScript 后台同步将停止工作

javascript - 在 Google 文档中添加文本和删除文本(插件)

javascript - 输入 "process"关键字时,使用 JavaScript 文件的 VS Code 出现 IntelliSense 问题

jquery - 返回所有 JSON 值的平均值

javascript - 如何使用 if & for 函数从 firestorage 数组值中查找特定行

javascript - DataTable 在更新行后不会重新绘制

javascript - jQuery 1.8 中的 pipe() 和 then() 文档与现实