Show Redirecting In.. CountDown Timer PHP

21,277

Solution 1

<script type="text/javascript">

(function () {
    var timeLeft = 5,
        cinterval;

    var timeDec = function (){
        timeLeft--;
        document.getElementById('countdown').innerHTML = timeLeft;
        if(timeLeft === 0){
            clearInterval(cinterval);
        }
    };

    cinterval = setInterval(timeDec, 1000);
})();

</script>

Redirecting in <span id="countdown">5</span>.

You can try this.

Solution 2

As this is a common beginner question; I just wanted to highlight that for best practise setInterval should, and can usually be avoided by using setTimeout recursively within a function.

For example:

var timer = 5,
    el = document.getElementById('countdown');

(function t_minus() {
    'use strict';
    el.innerHTML = timer--;
    if (timer >= 0) {
        setTimeout(function () {
            t_minus();
        }, 1000);
    } else {
        // do stuff, countdown has finished.
    }
}());
Share:
21,277
max_
Author by

max_

Engineering Lead

Updated on February 06, 2020

Comments

  • max_
    max_ about 4 years

    I have this code so far that redirects the user after 5 seconds to the correct URL:

    <?php $url = $_GET['url']; header("refresh:5;url=$url"); include('ads.php'); ?>

    Please could you tell me how i could display a countdown timer saying Redirecting In.. with .. being the amount of seconds left. I am new to web development so all code will be helpful!