Snippet. JavaScript. Redirect User After Specified Seconds with Countdown Message

This snippet shows a nice message to the user that he will be redirected to another page in couple of seconds. It also counts down the seconds. It is useful for flash messages displaying errors or successful actions.

<div style="padding:10px;font-size:11px;">
    You will be automatically redirected in <span id="countdown">10</span> s.
</div>

<script type="text/javascript">
function countdown(num){
    document.getElementById("countdown").innerHTML = num;
    if (num > 0) {
        setTimeout("countdown("+(num-1)+")",1000);
    } else{
        window.location.href="{$url}";
    }
}

countdown(10); // Set seconds to redirection
</script>

Updated on: 29 Mar 2024