jquery интервалы в отложенных объектах - PullRequest
0 голосов
/ 25 апреля 2018

В прошлом я использовал без отложенных объектов 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 Ответ

0 голосов
/ 25 апреля 2018

Я бы сделал это так

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