而vs setInterval

时间:2014-10-08 12:33:21

标签: javascript jquery loops

我有以下数组来监控我正在处理的应用程序启动的小部件:

widgets = [{
 selector: ".table",
 init: function() {...}
},
{
 selector: ".anothertable",
 init: function() {...}
}]

每个init函数都在调用一个插件。当插件完成任务时 它将选择器(例如“.table”)推送到另一个名为“readyWidgets”的数组

现在的问题是:

如果嵌套在主要小部件数组下的所有选择器,我该如何判断 是否存在于readyWidgets数组中?

我有点停电,虽然我有一个解决方案,但我认为有一个更好的我想念。

这就是我提出的:

init: function() {
    // this will hold each widget selector
    // and look for it later in readyWidgets array
    var widgetsPending = []

    // initialize each widget in widgets array
    // (only if the selector matches at least one element)
    this.widgets.forEach(function(widget) {
        $(widget.selector).length && widgetsPending.push(widget.selector) && widget.init()
    }, this)

    // use setInterval to check if all values in widgetsPending array
    // are present within this.readyWidgets
    var that = this
    var interval = setInterval(function() {
        // temporary just to make sure the interval is cleared
        console.log(that.readyWidgets)

        // if a value in widgetsPending is not found in 
        // that.readyWidgets, pageReady will be marked false
        var pageReady = true
        widgetsPending.forEach(function(selector) {
            if (that.readyWidgets.indexOf(selector) == -1) {
                pageReady = false
            }
        })

        // if widgetsReady is true, clear the interval
        pageReady && clearInterval(interval)
    }, 300)     
}

如果您对如何改进这一点有任何建议,请告诉:)

1 个答案:

答案 0 :(得分:2)

这样的事情:

var loadOperations = [];

objects.forEach(function (obj) {
    var loadComplete = $.Deferred();

    loadOperations.push(loadComplete);

    // long running async function call. this function can return deferred or promise as well
    obj.someLongRunningEGLoadOperation(function() { // async function complete callback
        loadComplete.resolve();
    });
});

$.when.apply($, loadOperations).done(function () {

    // do something then all long running operations are completed

});