1

setTimeout で 5 秒ごと jQuery 関数を実行していますが、div をクリックしてプロセスを停止するにはどうすればよいですか?

私のコードは次のとおりです。

function crono(selection){
    $.ajax({
        type: 'GET', 
        url: 'my_page.php', 
        data: {
            my_page: selection.attr('id')
        },
        success: function(data, textStatus, jqXHR) {
            selection.html(data);   
        }
    });
}


function repeat(){
    setTimeout(function() {
        $('.toReload').each(function(){
            crono($(this));
        });
        repeat();
    }, 5000);
}

repeat();
4

5 に答える 5

1

これを行うにはフラグを使用します。

var end = false;

function repeat(){
   setTimeout(function() {
      if(!end){ 
          $('.toReload').each(function(){
            crono($(this));
          });
          repeat();
      }     
   }, 5000);
}
...

$('#div').click(function(){
 end = true;
});
于 2013-07-03T12:53:48.700 に答える
1

clearTimeout https://developer.mozilla.org/fr/docs/DOM/window.clearTimeoutを使用します:

var handle = null;

function repeat(){
    handle  = setTimeout(function() {
        $('.toReload').each(function(){
            crono($(this));
        });
        repeat();
    }, 5000);
}

setTimeoutを呼び出してキャンセルします:

clearTimeout(handle);
于 2013-07-03T12:51:23.230 に答える
0

明確なタイムアウトと ajax リクエストが必要です。

    var getData = {
    handleTimeout : 0,
    handleAjax,

    crono : function(selection){
        $.ajax({
            type: 'GET', 
            url: 'my_page.php', 
            data: {
                my_page: selection.attr('id')
            },
            success: function(data, textStatus, jqXHR) {
                selection.html(data);   
            }
        });
    },

    repeat: function(){
        this = ob;
        this.handleTimeout = setTimeout(function() {
            $('.toReload').each(function(){
                ob.crono($(this));
            });
            repeat();
        }, 5000);
    },

    stopAll: function(){
        clearTimeout(this.handleInterval);
        this.handleAjax.abort();
    }
}

getData.repeat();
getData.stopAll();
于 2013-07-03T13:09:16.463 に答える