闯入循环的javascript函数的方法

toz*_*iah 1 javascript

我希望已经有一百万个答案了,而且我不知道用来说明这个问题的术语.但...

看看这个:http://jsfiddle.net/QD3UK/8/

$('body').on('click', '.testDiv', function(){
    console.log($(this))
    repeatTest(1)
})

function repeatTest(n){
    window.setTimeout(function(){
        $('.result').append(n+" hi<br />")
        repeatTest(n);
    }, 3000);
    n++
}
Run Code Online (Sandbox Code Playgroud)

我希望循环函数在再次单击testDiv div时再次启动 - 因此只有一个循环迭代 - 它从哪个数字(n)开始并不重要.

请帮忙?谢谢

Joe*_*nos 5

您可以clearTimeout取消现有的setTimeout.所以类似于:

var _handle;

$('body').on('click', '.testDiv', function(){
    clearTimeout(_handle);
    console.log($(this))
    repeatTest(1)
});

function repeatTest(n){
    _handle = window.setTimeout(function(){
        $('.result').append(n+" hi<br />")
        repeatTest(n);
    }, 3000);
    n++;
}
Run Code Online (Sandbox Code Playgroud)