Search code examples
javascriptjquerycountdown

Countdown in JS


I'm trying to have, on a registered.php page, a countdown that shows a timer that starts from 3 secs and goes down second by second, redirecting to another page in the end. However, when I load the page in my browser i'm redirected to the other page in an instant. Can someone help me figure out why?

    The registration was successful, you will be redirected in <span id="num"></span> seconds.
    <script>
        $(document).ready(function (){
            for (var i = 3; i>0; i--) {
                setTimeout(function () {
                    $("#num").html(i);
                },1000);
            }
            window.location.replace("login.html");
        });
    </script>

Solution

  • Since this is a redirection page, you might not want to include the whole jQuery library for this bit of code:

    var remaining = 3;
    
    function countdown() {
        document.getElementById('num').innerHTML = remaining;
        if (!remaining--) {
            window.location.replace("login.html");
        }
        setTimeout(countdown, 1000);
    }
    
    window.onload = countdown;
    

    JS Fiddle Demo