Mike Mike - 2 months ago 11x
Javascript Question

setTimeout() is not waiting

I am trying to make a seconds countdown with Javascript.

Here is my HTML

<div id="ban_container" class="error center">Please wait
<span id="ban_countdown" style="font-weight:bold">
seconds before trying again

And my JS:

<script type="text/javascript">
var seconds = <?php echo $user->getBlockExpiryRemaining(); ?>;

function countdown(element) {
var el = document.getElementById(element);

if (seconds === 0) {
document.getElementById("ban_container").innerHTML = "done";
else {
el.innerHTML = seconds;
setTimeout(countdown(element), 1000);


However for some reason, it is not waiting the timeout time, but instead executes
right away so that when I refresh the page it just displays "done" right away. I know it is actually being executed multiple times because if I do
innerHTML += seconds + " ";
it counts down from 45. Why is the timeout being bypassed?


setTimeout(countdown(element), 1000); executes your function with that argument and passes the result into setTimeout. You don't want that.

You want to execute a function that calls your code:

setTimeout(function() {
    countdown(el);  // You used `el`, not `element`?
}, 1000);