views:

315

answers:

3

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 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 ?

A: 

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...

Plan B
actually this is a simplified version of my script; my original script is a plugin that uploads pictures. so when i click on mu button i want to upload a picture(using an iframe)...and when the picture is loaded...my php file writes "<p>1</p>" in my iframe...so i check with that setTimeout if the file is uploaded or not. so each time when i click on my button i want to upload a picture. So what can i do with that flag?
kmunky
A: 

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.

Shankar Ramachandran
pfff...i can;t make it work...can you show me the answer on my code?
kmunky
A: 

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

Josh Stodola
ok, but where exactly should i call clearTimeout in my code?
kmunky
...before calling setTimeout.
Joel Mueller