Okay, so there is a button on a page that I'm trying to change the text of for a count-down done in Javascript. I'm fairly new to the language (2 days), and am not sure as to what is wrong with my code. Instead of waiting the full second before iterating again, it instantly re-iterates.
var c = 15;
function countDown(e){
if (c!=0){
e.value = 'Reply (' + c + ')';
c--;
setTimeout(countdown(e),1000);
}
else{
e.value = 'Reply'}
}
}
but it seems that instead of taking 15 seconds like I assumed, it fires off all at once (proven by me adding in an alert('a');
in the if statement I could see the button text changing)
I'm not sure if it's a problem with Greasemonkey or a problem with my javascript.
Your problem is with this line:
setTimeout(countdown(e),1000);
countdown(e)
is a call to the countdown function that returns void. The setTimeout function accepts a function reference and a timeout, so you need to change it to:
setTimeout(countdown, 1000);
Your current code is calling countdown(e) 15 times recursively and then setTimeout(void, 1000);
If you need setTimeout to pass arguments (like e
) to your function you can make use of the optional parameters after the timeout.
setTimeout(countdown, 1000, e);