延迟对象的jQuery间隔



我过去曾经使用jQuery递延对象而没有问题,我了解它们的工作方式。

我现在遇到了一个新情况,我需要再次使用它们。

我有一些类似的功能,我将其添加到递延数组中。这些功能使用AJAX每5秒获取一个值,直到计数器达到0

deferreds.push(
    getQueueCount()
);
function getQueueCount()
{
    var counter = 1,
        intervalId = setInterval(function() {
            if(counter > 0) {
                $.ajax({
                    type: 'POST',
                    url: 'path/to/script',
                    dataType: 'json',
                    data: {
                        'queuename': 'myqueue',
                        'total' : 10
                    },
                    success: function(response) {
                        $('#progress').width(response.width + "%").find('span').text(response.width + '%');
                        counter = response.size;
                    }
                });
            }
            else {
                clearInterval(intervalId);
                intervalId = null;
                counter = 1;
                return intervalId;
            }
        }, 5000);
}

但是,当我运行以下代码时,该按钮将启用

$.when.apply($, deferreds).done(function() {
    $('#btn-sync').prop('disabled', false);
});

我的问题是如何防止按钮启用直到我的功能完成?当每个功能中的计数器达到0

时,我需要将功能分为完整

我会像这样做

function getQueueCount()
{
    var dfrQueue = new $.Deferred(),
        counter = 1,
        intervalId = setInterval(function() {
            if(counter > 0) {
                $.ajax({
                    type: 'POST',
                    url: 'path/to/script',
                    dataType: 'json',
                    data: {
                        'queuename': 'myqueue',
                        'total' : 10
                    },
                    success: function(response) {
                        $('#progress').width(response.width + "%").find('span').text(response.width + '%');
                        counter = response.size;
                    }
                });
            }
            else {
                dfrQueue.resolve('queue');
                clearInterval(intervalId);
                counter = 1;
            }
        }, 5000);
     console.log('initialize test for queue');
     return dfrQueue.promise();
}
$.when.apply($, deferreds).then(function(arg) {
    // all operations has completed and console out the argument provided by the last operation that completed.
    console.log('all process succeeded: ' + arg);
});

最新更新