代码之家  ›  专栏  ›  技术社区  ›  AdRock

延迟对象中的jquery间隔

  •  1
  • AdRock  · 技术社区  · 6 年前

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

    1 回复  |  直到 6 年前
        1
  •  1
  •   Peter Griffin    6 年前

    我会这样做

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