【问题标题】:jquery intervals in deferred objects延迟对象中的jQuery间隔
【发布时间】:2018-04-25 09:24:30
【问题描述】:

我过去使用过 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 时,我需要将该函数归类为完整

【问题讨论】:

    标签: jquery ajax setinterval jquery-deferred clearinterval


    【解决方案1】:

    我会这样做

    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);
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-17
      • 1970-01-01
      • 1970-01-01
      • 2017-07-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多