开发者

javascript/jQuery setTimeout

开发者 https://www.devze.com 2022-12-09 06:11 出处:网络
i have this code: $(\'.myButton\').live(\'click\',function(){ var checkTextValue = setTimeout(function() {

i have this code:

$('.myButton').live('click',function(){
    var checkTextValue = setTimeout(function() {
    var textVal = $('p').text();
    if (textVal == 'expectedValue'){
        alert('done');
    } else {
       setTimeout(arguments.callee, 10);
    }
    },10);
 });

when the button is clicked for the first time it works just fine, but when the button is clicked more than开发者_JAVA技巧 once alert is called n+ times(if i click one more time on the button an alert pops->i click "ok" and then one more alert pops; after this if i click one more time 3 alerts pops); is there any way to remove the function after textVal == 'expectedValue' returns true ?


You could try putting a return false; at the end of that branch of the if statement?

Alternatively, you could simply set a flag such as hasRun = 1, and simply check for that value before you run anything inside that branch of the if statement...


You need to clear the timeout (using clearTimeout) before calling setTimeout to prevent simultaneous executions.


In the else condition you are just setting the time-out...you should also be updating the value of your 'expectedValue'...right?

And return the boolean value accordingly for the conditional.

You could use a new boolean flag...or use existing values for the same purpose. Let me know if you need elaboration.


You could use setInterval() to achieve this rather than setTimeout():

var intervalId = 0;
$('.myButton').live('click', function(){
    if (intervalId != 0) {
        clearInterval(intervalId);
    }
    intervalId = setInterval(function() {
        var textVal = $('p').text();
        if (textVal == 'expectedValue'){
            clearInterval(intervalId);
            intervalId = 0;

            alert('done');
        }
    }, 10);
});

Another advantage of this approach is that you can determine if they have already clicked it and mention that this is already being checked.

var intervalId = 0;
$('.myButton').live('click', function(){
    if (intervalId != 0) {
        alert('check already in progress... please wait');
        return false;
    }
    intervalId = setInterval(function() {
        var textVal = $('p').text();
        if (textVal == 'expectedValue'){
            clearInterval(intervalId);
            intervalId = 0;

            alert('done');
        }
    }, 10);
});

Alternatively you could prompt them and ask the user if they would like to stop the checking (in this case simply clear the interval and set intervalId to 0).

0

精彩评论

暂无评论...
验证码 换一张
取 消