JQuery: I want to refresh when countdown reaches zero - javascript

I want to refresh when countdown reaches zero.
window.location.reload();
So I added a refresh to countdown <= 0.
However, the refresh is infinite.
How can I do a single refresh after the countdown reaches zero?
The refresh script is:
$(document).ready(function() {
endTimeCheck();
window.setInterval(function() {
endTimeCheck();
}, 1000);
});
var timestamp = Math.floor(Date.now() / 1000);
function endTimeCheck() {
$("span[name='betStatus']").each(function() {
var $span = $(this);
var play_timestamp = parseInt($(this).attr("timestamp"));
var countdown = play_timestamp - timestamp - 32700;
if (countdown <= 0) {
if (!$span.hasClass('closed')) {
$span.css("color", "#FF5733").css("font-weight", "bold").text("finish");
var tdObj = $span.parents('.event-list-item').addClass("disable");
window.location.reload();
}
}
// 30분
else if (countdown < 1800) {
var minute = Math.floor(countdown / 60);
var second = countdown % 60;
if (second < 10) {
second = "0" + second;
}
$(this).css("color", "DarkOrange").css("font-weight", "bold").text(minute + ":" + second);
}
// 1시간
else if (countdown <= 3600) {
var minute = Math.floor(countdown / 60);
var second = countdown % 60;
if (second < 10) {
second = "0" + second;
}
$(this).css("font-weight", "bold").text(minute + ":" + second);
}
});
timestamp++;
}

I think the best way to achieve this is using cookies.
When your countdown reach 0, you set a cookie (ie: refreshed, true).
Don't forget to check if the cookie doesn't exists before your countdown function.
document.cookie = 'refreshed=true';
You can also set an expiration time if you want your function to be re-enabled every 2hs.
var now=new Date();
var expireTime=new Date();
expireTime.setHours(now.getHours()+2);
document.cookie = 'refreshed=true; expires='+expireTime.toGMTString();

Related

Countdown timer - make it persistent even after refresh or reload

I have a html page where there is counter starts on page loading. But the problem is if someone refresh or reloads the page the counter restarts. I dont know how to use local storage or cookies to make sure my counter does not reset upon reload. I am aware of the similar questions available here but my issue is i want local storage to be part of a function (countDown()).
Here is the code I tried:
<script>
var timer;
function countDown(i, callback) {
//callback = callback || function(){};
timer = setInterval(function() {
minutes = parseInt(i / 60, 10);
seconds = parseInt(i % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
document.getElementById("displayDiv ").innerHTML = "Time (h:min:sec) left for this station is " + "0:" + minutes + ":" + seconds;
i-- || (clearInterval(timer), callback());
}, 1000);
}
window.onload = function() {
countDown(60, function() {
$('#myModal').modal('show');
});
};
</script>
First, persist your current counter value to the session storage (with a specific key) at each iteration. You may only persist/update the value when the counter is greater than 0, and then clear the storage key once counter reached 0.
const COUNTER_KEY = 'my-counter';
function countDown(i, callback) {
//callback = callback || function(){};
timer = setInterval(function() {
minutes = parseInt(i / 60, 10);
seconds = parseInt(i % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
document.getElementById("displayDiv").innerHTML = "Time (h:min:sec) left for this station is " + "0:" + minutes + ":" + seconds;
if ((i--) > 0) {
window.sessionStorage.setItem(COUNTER_KEY, i);
} else {
window.sessionStorage.removeItem(COUNTER_KEY);
clearInterval(timer);
callback();
}
}, 1000);
}
Then on the window.onload function, first check if there is a value under the above key on the session storage. If a value is there, start the countdown from that value. Otherwise, start from your default value (60).
window.onload = function() {
var countDownTime = window.sessionStorage.getItem(COUNTER_KEY) || 60;
countDown(countDownTime, function() {
$('#myModal').modal('show');
});
};
You can try using localStorage as follows:
var timer;
function countDown(i, callback) {
//callback = callback || function(){};
timer = setInterval(function () {
minutes = parseInt(i / 60, 10);
seconds = parseInt(i % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
document.getElementById("displayDiv").innerHTML = "Time (h:min:sec) left for this station is " + "0:" + minutes + ":" + seconds;
// update the persisted time interval
localStorage.setItem('timeLeft', i);
i-- || (clearInterval(timer), callback());
}, 1000);
}
window.onload = function () {
let timeInterval = 100;
//check if you have the last counter value
let timeLeft = localStorage.getItem('timeLeft');
if (isNaN(timeLeft)) {
//save the current interval
localStorage.setItem('timeLeft', timeInterval);
} else if (timeLeft == 0) {
//save the current interval
localStorage.setItem('timeLeft', timeInterval);
} else {
// take the last saved value
timeInterval = timeLeft;
}
countDown(timeInterval, function () {
$('#myModal').modal('show');
});
};
I think what you want is a property called sessionStorage which stores information in the browser permanently.
here's a link explaining it
https://www.w3schools.com/jsref/prop_win_sessionstorage.asp
I have a made a promise based function for this.
It uses localStorage to store the countdown every 1 second and, once the time is over, it returns you a promise.
I use it with React and React Router on production, it's been working great.
function countdown(interval = 5000) {
return new Promise(async (resolve, reject) => {
let intervalLoop = null
function countTimer() {
if (!localStorage.endTime) {
localStorage.endTime = +new Date() + interval
}
let remaining = localStorage.endTime - new Date()
if (remaining >= 0) {
let currentTime = Math.floor(remaining / 1000)
console.log("Countdown current time:", currentTime)
} else {
clearInterval(intervalLoop)
resolve(true)
}
}
intervalLoop = setInterval(countTimer, 1000)
})
}
Make sure you are inside an async function to use it:
(async _ => {
console.log("Countdown starts now...")
await countdown(5000)
console.log("Countdown is over!");
})()

window.location.reload doesn't work

I have a timer on my page for 10 min. and when time exceed page supposed to refresh itself and remove the session values.
It was working very well but suddenly it stopped working.. Timer gets stuck at 0:01.
It's look like when location.reload() executes then page get stuck. Explorer's status bar keep showing the loading icon.. over and over again.
My code is below:
<script>
var counter = setInterval(timer, 1000);
function timer() {
count = count - 1;
// if time exceed then refresh the page.
if (count <= 0) {
location.reload();
}
else
{
var timerSpan = document.getElementById("timerCountdown");
if (count <= timerTurnToRed) {
//Make Red
timerSpan.className = "finalCountdown";
}
// Calculate remaining minutes & seconds
var remainingMinutes = Math.floor(count / 60)
// Check if it is negative
if (remainingMinutes < 0)
location.reload();
var remainingSecs = count - (remainingMinutes * 60);
if (remainingSecs < 10) {
remainingSecs = "0" + remainingSecs.toString();
}
timerSpan.innerHTML = remainingMinutes + ":" + remainingSecs;
}
}
</script>
Don't get where is the problem it works as expected. StackOverflow code evaluator will prevent reloading.
var count = 15;
var timerTurnToRed = 10;
var counter = setInterval(timer, 1000);
function timer() {
count--;
// if time exceed then refresh the page.
if (count <= 0) {
location.reload();
}
else
{
var timerSpan = document.getElementById("timerCountdown");
if (count <= timerTurnToRed) {
//Make Red
timerSpan.className = "finalCountdown";
}
var remainingMinutes = Math.floor(count / 60);
// Check if it is negative
if (remainingMinutes < 0)
location.reload();
var remainingSecs = count - (remainingMinutes * 60);
if (remainingSecs < 10) {
remainingSecs = "0" + remainingSecs.toString();
}
timerSpan.innerHTML = remainingMinutes + ":" + remainingSecs;
}
}
.finalCountdown {color: red;}
<div id="timerCountdown"></div>

Prevent Javascript coundown timer reset when page is refreshed

i'm a newbie here. I know there is similar question on this but still i don't get it. Sorry for that. I'm hoping for an answer on this.
I have a 30 seconds countdown timer. How to prevent it from resetting?
Here is the code:
<html>
<body>
<div id="timer"></div>
<script>
var count = 1801; // 30 seconds
var counter = setInterval(timer, 1000); //1000 will run it every 1 second
function timer() {
count = count - 1;
if (count == -1) {
clearInterval(counter);
document.getElementById("submittime").click();
return;
}
var secondcount = count;
var seconds = count % 60;
var minutes = Math.floor(count / 60);
var hours = Math.floor(minutes / 60);
minutes %= 60;
hours %= 60;
document.getElementById("timer").innerHTML = hours + ":" + minutes + ":" + seconds;
}
</script>
</body>
</html>
I want to use the code above and merge it to this.
Currently this code is a timer from 0 to 10 and not being refreshed by the browser. I dont know how to do it with hour, minute, second.
<body>
<div id="divCounter"></div>
<script type="text/javascript">
if(localStorage.getItem("counter")){
if(localStorage.getItem("counter") >= 10){
var value = 0;
}else{
var value = localStorage.getItem("counter");
}
}else{
var value = 0;
}
document.getElementById('divCounter').innerHTML = value;
var counter = function (){
if(value >= 10){
localStorage.setItem("counter", 0);
value = 0;
}else{
value = parseInt(value)+1;
localStorage.setItem("counter", value);
}
document.getElementById('divCounter').innerHTML = value;
};
var interval = setInterval(function (){counter();}, 1000);
</script>
</body>
Usually the client side javascript is reloaded when the page is reloaded. that's how it works. According to my knowledge the best way is to,
Store the countdown value in a Cookie or Local Storage and on page load continue from that value.
This approach uses localStorage and does not Pause or Reset the timer on page refresh.
<p id="demo"></p>
<script>
var time = 30; // This is the time allowed
var saved_countdown = localStorage.getItem('saved_countdown');
if(saved_countdown == null) {
// Set the time we're counting down to using the time allowed
var new_countdown = new Date().getTime() + (time + 2) * 1000;
time = new_countdown;
localStorage.setItem('saved_countdown', new_countdown);
} else {
time = saved_countdown;
}
// Update the count down every 1 second
var x = setInterval(() => {
// Get today's date and time
var now = new Date().getTime();
// Find the distance between now and the allowed time
var distance = time - now;
// Time counter
var counter = Math.floor((distance % (1000 * 60)) / 1000);
// Output the result in an element with id="demo"
document.getElementById("demo").innerHTML = counter + " s";
// If the count down is over, write some text
if (counter <= 0) {
clearInterval(x);
localStorage.removeItem('saved_countdown');
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
</script>

javascript count down timer flickering on calling more than once

function countdown(element, minutes, seconds) {
// set time for the particular countdown
var time = minutes*60 + seconds;
var interval = setInterval(function() {
var el = document.getElementById(element);
// if the time is 0 then end the counter
if(time == 0) {
//el.innerHTML = "countdown's over!";
// document.getElementById("timer").style.visibility="hidden";
clearInterval(interval);
return;
}
var hour=Math.floor( time / (60*60) );
if (hour < 10) hour = "0" + hour;
var minutes = 0;
if(time>=60 && hour>0)
minutes=Math.floor( (time / 60 )-60);
else{
minutes=Math.floor( (time / 60 ));
}
if (minutes < 10) minutes = "0" + minutes;
var seconds = time % 60;
if (seconds < 10) seconds = "0" + seconds;
// var text = hour+":"+minutes; //+ ':' + seconds;
var text = minutes; //+ ':' + seconds;
el.innerHTML = text;
time--;
}, 1000);
}
when i am calling the method 2wice, its creating flickering effect.
i.e. countdown(element, 50, 0);
it count downs but if i call it again i.e. countdown(element, 35, 0); it is flicks showing both the countddowns
You need to cancel the interval when the plugin initializes if you are going to call it on the same element. Otherwise you are running two intervals at once.
I'd suggest returning the interval from your function and allowing yourself to pass that interval in as a parameter. That way you can always cancel the interval before starting it (in case there is already one going). If you pass null for the interval var, you can still run clearInterval() without throwing errors.
For example:
function countdown(element, minutes, seconds, interval) {
// set time for the particular countdown
var time = minutes*60 + seconds;
clearInterval(interval);
return setInterval(function() {
...
Your first call could be:
var savedInterval = countdown('some-ele-id', 1, 1, null);
And your second call could be:
var interval = countdown('some-ele-id', 1, 1, savedInterval);
Another solution would be to save the interval as a global variable and cancel it without passing it as a parameter inside your plugin.
An alternative to avoid modify your code is:
var interval;
...
function countdown(element, minutes, seconds) {
// set time for the particular countdown
var time = minutes*60 + seconds;
interval = setInterval(function() {
...
And in your second call:
clearInterval(interval);
countdown(element, 35, 0);

javascript countdown stutter

I have a countdown like this one:
var countdown = {
startInterval: function() {
var count = 600
var countorig = 600;
var currentId = setInterval(function() {
var min = (count - (count % 60)) / 60;
var sec = count % 60;
if (sec < 10) {
$('#timer').html(min + ':0' + sec);
} else {
$('#timer').html(min + ':' + sec);
}
$('#time').val(countorig - count);
if (count == 0) {
$('#form').submit();
}--count;
}, 1000);
countdown.intervalId = currentId;
}
};
It works. But if I load the page, the countdown starts but it stutter it is not "round" like a clock is.
JSFiddle.
setInterval isn’t exact. You should use Dates instead, to get an accurate time, and then choose an interval of less than one second to get a smoother clock. Here’s a demo!
var countdown = {
startInterval: function() {
var count = 600;
var start = new Date(); // The current date!
var currentId = setInterval(function() {
var difference = Math.max(0, count - (new Date() - start) / 1000 | 0);
var min = difference / 60 | 0;
var sec = difference % 60;
$('#timer').text(min + ':' + (sec < 10 ? '0' : '') + sec);
$('#time').val(difference);
if(count === 0) {
$('#form').submit();
}
}, 200);
countdown.intervalId = currentId;
}
};
It's never a good idea to assume your timers are exact. Instead, use delta timing.
var startTime = new Date().getTime();
setInterval(function() {
var elapsed = new Date().getTime()-startTime;
console.log("Been running for "+Math.floor(elapsed/1000)+" seconds");
},25);
That is because setInterval is not meant to be a high resolution timer. It will NOT hit every 1000 milliseconds on the dot. You might have swings as much as 20 to 30 milliseconds in either direction, resulting in a clock that is off.
Using Date.now(), this is a quick example of a countdown function ( x is milliseconds )
function countdown(x){
var o = {future: Date.now()+x, last:-1, i:null}; // object so we can pass by-ref if req.
o.i = setInterval( function() { // use o.i so we can clear interval
var remain = o.future - Date.now(),
secs = Math.floor( remain / 1000 ),
mins = 0;
if( remain < 0 ){ // finished, do whatever
return clearInterval(o.i); // then clear & exit
}
if( secs === o.last ) return; // skip this iteration if it's not been a second
o.last = secs; // else update last time
// do whatever you want for this new second
if( secs > 59 ) mins = Math.floor( secs / 60 ), secs = secs % 60;
console.log(
(mins < 10 ? '0'+mins : mins) + ':' +
(secs < 10 ? '0'+secs : secs) + ' remain.'
);
}, 100);
}
If you know it wont be used in IE, consider adding o as an argument to the callback function in the interval and also as the last argument to setInterval (so it is passed to the callback as first arg), which means closure is independent => callback can be defined anywhere.

Categories