I have a countdown javascript script, and I want my page to refresh once when the countdown ends.
Here is my complete 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 to update:
location.reload();
If I add this update code to this part of the code below, the operation will update.
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 update method is updated every second after the countdown ends. But I want it to be updated only once when it hits 0.
What have i tried?
I tried to create another if statement to refresh the page when t.total == 0 , for example:
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 for some reason this did not work.
So, I also tried with if (t.total = 0) and if (t.total === 0) , but still can't handle it.
Can someone give me a hand to refresh the page when the counter hit 0?
Here is jsFiddle for you if you want to play: https://jsfiddle.net/qv6rbyLo/1/