johnny456
johnny456

Reputation: 79

How to redirect a page after countdown reaches zero?

I have this javascript countdown code:

function getTimeRemaining(deadline) {
    var t = Date.parse(deadline) - Date.parse(new Date),
    s = Math.floor(t / 1e3 % 60),
    m = Math.floor(t / 1e3 / 60 % 60),
    h = Math.floor(t / 36e5 % 24),
    d = Math.floor(t / 864e5); 
return {
    total: t,
    seconds: s
    minutes: m,
    hours: h,
    days: d
}
}

function initializeClock(clockdiv, deadline) {
var cla = document.getElementById(clockdiv),
    days = cla.querySelector(".days"),
    hours = cla.querySelector(".hours"),
    minutes = cla.querySelector(".minutes"),
    seconds = cla.querySelector(".seconds");

function abc() {
    var time = getTimeRemaining(deadline);
    days.innerHTML = ("0" + time.days).slice(-2),
    hours.innerHTML = ("0" + time.hours).slice(-2),
    minutes.innerHTML = ("0" + time.minutes).slice(-2),
    seconds.innerHTML = ("0" + time.seconds).slice(-2),
    time.total <= 0 && clearInterval(s)
}
abc();
var s = setInterval(abc, 1e3)
}

How can i make it so it redirects on countdown reaching zero? Any help very appreciated! Thanks!

Upvotes: 1

Views: 734

Answers (1)

Hasitha
Hasitha

Reputation: 152

You can use following code snippet to handle redirections after certain time frame.

Suggestion on using calendar deadlines would be to use millisecond value of given deadline and subtract it with current time and set the timeout value.

Credit should go to https://gist.github.com/Joel-James/62d98e8cb3a1b6b05102

<!-- Modify this according to your requirement -->
<h3>
Redirecting to Google.com after <span id="countdown">10</span> seconds
</h3>
<!-- JavaScript part -->
<script type="text/javascript">

// Total seconds to wait
var seconds = 10;

function countdown() {
    seconds = seconds - 1;
    if (seconds < 0) {
        // Chnage your redirection link here
        window.location = "https://google.com";
    } else {
        // Update remaining seconds
        document.getElementById("countdown").innerHTML = seconds;
        // Count down using javascript
        window.setTimeout("countdown()", 1000);
    }
}

// Run countdown function
countdown();

</script>

Upvotes: 2

Related Questions