Search code examples
javascriptphpcountdown

How to stop countdown after zero


i try to create a javascript to countdown then redirect to another site.

but when it reach zero and page loading, countdown start to count -1, -2, etc. up to redirect to another page.

Here what I have try:

function countdown(remaining) {
    if(remaining === 0)
        window.location = '<?php echo $link_redirect ?>';
    document.getElementById('countdown').innerHTML = remaining;
    setTimeout(function(){ countdown(remaining - 1); }, 1000);
};

Solution

  • Simply adding the condition to only count down when remaining is more than 0

    function countdown(remaining) {
        document.getElementById('countdown').innerHTML = remaining;
        if(remaining > 0) {
            setTimeout(function(){ countdown(remaining - 1); }, 1000);
        } else {
            window.location = '<?php echo $link_redirect ?>';
        }
    ;