简体   繁体   中英

Refreshing page when countdown ends

I have a javascript countdown script, and I want my page to refresh for once when countdown ends.

Here is my full code.

//JavaScript code for countdown
function getTimeRemaining(endtime) {
  var t = Date.parse(endtime) - Date.now();
  var seconds = Math.floor((t / 1000) % 60);
  var minutes = Math.floor((t / 1000 / 60) % 60);
  var hours = Math.floor((t / (1000 * 60 * 60)) % 24);
  var days = Math.floor(t / (1000 * 60 * 60 * 24));
  return {
    'total': t,
    'days': days,
    'hours': hours,
    'minutes': minutes,
    'seconds': seconds
  };
}

function initializeClock(id, endtime) {
  var clock = document.getElementById(id);
  var daysSpan = clock.querySelector('.days');
  var hoursSpan = clock.querySelector('.hours');
  var minutesSpan = clock.querySelector('.minutes');
  var secondsSpan = clock.querySelector('.seconds');

  function updateClock() {
    var t = getTimeRemaining(endtime); 



if (t.total < 0) {
  document.getElementById("clockdiv").className = "hidden-div";
  document.getElementById("timeIsNow").className = "visible-div";
  clearInterval(timeinterval);
  return true;
}

daysSpan.innerHTML = t.days;
hoursSpan.innerHTML = ('0' + t.hours).slice(-2);
minutesSpan.innerHTML = ('0' + t.minutes).slice(-2);
secondsSpan.innerHTML = ('0' + t.seconds).slice(-2);

  }

  updateClock();
  var timeinterval = setInterval(updateClock, 1000);
}

var deadline = '2015-12-31T13:00:00+02:00';
console.log(deadline);

initializeClock('clockdiv', deadline);

This is the code I want to use for refresh:

location.reload();

If I add this refreshing code in this part of code below, refresh works.

if (t.total < 0) {
  document.getElementById("clockdiv").className = "hidden-div";
  document.getElementById("timeIsNow").className = "visible-div";
  clearInterval(timeinterval);
  location.reload(); //Added this one.
  return true;
}

However, this way refresh works every second after countdown ends. But I want it to refresh only once, when it hits to the 0.

What I tried?

I tried to create another if statement to refresh the page when t.total == 0 , like that:

if (t.total == 0) {
  document.getElementById("clockdiv").className = "hidden-div";
  document.getElementById("timeIsNow").className = "visible-div";
  clearInterval(timeinterval);
  location.reload(); //Added this one.
  return true;
}

But somehow, it didn't work.

So I also tried with, if (t.total = 0) and if (t.total === 0) but still can't work it out.

Can anyone give me a hand to refresh the page when counter hit to the 0?

Here is a jsFiddle if you would like to play: https://jsfiddle.net/qv6rbyLo/1/

The problem is that when you refresh the page, you start the clock again. Then it finishes immediately, triggering another refresh.

You need to check for the possibility that the deadline has already passed , and then only refresh if the deadline hadn't already passed when you started the clock.

Here's an updated initializeClock (see comments):

function initializeClock(id, endtime, callback) {       // <== Add callback
    var clock = document.getElementById(id);
    var daysSpan = clock.querySelector('.days');
    var hoursSpan = clock.querySelector('.hours');
    var minutesSpan = clock.querySelector('.minutes');
    var secondsSpan = clock.querySelector('.seconds');
    var ranOnce = false;                                // <== Haven't run once yet

    var t = getTimeRemaining(endtime);

    function updateClock() {
        var t = getTimeRemaining(endtime);

        if (t.total < 0) {
            document.getElementById("clockdiv").className = "hidden-div";
            document.getElementById("timeIsNow").className = "visible-div";
            clearInterval(timeinterval);
            callback(ranOnce);                          // <== Tell callback whether we ran
            return true;
        }

        ranOnce = true;                                 // <== Flag that we ran at all
        daysSpan.innerHTML = t.days;
        hoursSpan.innerHTML = ('0' + t.hours).slice(-2);
        minutesSpan.innerHTML = ('0' + t.minutes).slice(-2);
        secondsSpan.innerHTML = ('0' + t.seconds).slice(-2);

    }

    var timeinterval = setInterval(updateClock, 1000);  // <=== Important that this is before the first call to updateClock
    updateClock();
}

...which you'd use like this:

initializeClock('clockdiv', deadline, function(ranOnce) {
    if (ranOnce) {
        location.reload();
    }
});

Here's a live example with a deadline in the future: https://jsfiddle.net/mzabLrvy/

And where the deadline is in the past: https://jsfiddle.net/mzabLrvy/1/

You can try using a GET parameter to stop refreshing your page.

Add this to your js code:

var _get = (function(a) {
if (a == "") return {};
var b = {};
for (var i = 0; i < a.length; ++i)
{
    var p=a[i].split('=', 2);
    if (p.length == 1)
        b[p[0]] = "";
    else
        b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
}
return b;
})(window.location.search.substr(1).split('&'));    

This will give you a neat access to the GET parameters from js.

Then you can write a refresh page function like this:

function refreshPage(){
    if (typeof _get["isRefreshed"] === "undefined")
        return;

    window.location.href = "index.htm?isRefreshed=1";
    // "index.htm" is the current page of course
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM