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>
Related
There is a counter that counts down from 25. When I click on the link of the page, it continues to count from wherever it is left. So when I start at 25 and exit the page, it shows 15 when I come back 10 seconds later. But when I open it with a different browser, there is a different number, so the counter does not always show the same value. What could be the reason for this and what can I do?
var interval = 25000;
function reset() {
localStorage.endTime = +new Date() + interval;
}
if (!localStorage.endTime) {
reset();
}
function millisToMinutesAndSeconds(millis) {
var seconds = ((millis % 60000) / 1000).toFixed(0);
return (seconds < 10 ? "0" : "") + seconds;
}
setInterval(function () {
var remaining = localStorage.endTime - new Date();
if (remaining >= 0) {
document.getElementById("timer").innerText =
millisToMinutesAndSeconds(remaining);
} else {
reset();
}
}, 100);
I have a countdown in js and I can't add a trick I would like.
When the counting ends, it does not stop. Negative numbers start and instead I would like it to stop at 0 once the time has expired. How can I?
var counter = null;
window.onload = function() {
initCounter();
};
function initCounter() {
// get count from localStorage, or set to initial value of 1000
count = getLocalStorage('count') || 1000;
counter = setInterval(timer, 1000); //1000 will run it every 1 second
}
function setLocalStorage(key, val) {
if (window.localStorage) {
window.localStorage.setItem(key, val);
}
return val;
}
function getLocalStorage(key) {
return window.localStorage ? window.localStorage.getItem(key) : '';
}
function timer() {
count = setLocalStorage('count', count - 1);
if (count == -1) {
clearInterval(counter);
return;
}
var seconds = count % 60;
var minutes = Math.floor(count / 60);
var hours = Math.floor(minutes / 60);
minutes %= 60;
hours %= 60;
document.getElementById("countdown").innerHTML = hours + " ore " + minutes + " min " + seconds + " sec";
}
The problem is that you were putting count with -1 value in LocalStorage.
count = setLocalStorage('count', count - 1);
And after page reload you kept subtracting 1 from -1 and you got -2, which your condition count == -1 couldn't catch. Solution is to put next count value in LocalStorage after you check if need to continue your timer or not.
<script type="text/javascript">
let count = 0;
let counter = null;
window.onload = function() {
initCounter();
};
function initCounter() {
// get count from localStorage, or set to initial value of 1000
count = Number(getLocalStorage('count')) || 5;
counter = setInterval(timer, 1000); //1000 will run it every 1 second
}
function setLocalStorage(key, val) {
if (window.localStorage) {
window.localStorage.setItem(key, val);
}
return val;
}
function getLocalStorage(key) {
return window.localStorage ? window.localStorage.getItem(key) : '';
}
function timer() {
const nextCount = count - 1
if (nextCount < 0) {
clearInterval(counter);
return;
}
count = setLocalStorage('count', nextCount);
const seconds = count % 60;
let minutes = Math.floor(count / 60);
let hours = Math.floor(minutes / 60);
minutes %= 60;
hours %= 60;
document.getElementById("timer").innerHTML = hours + " ore " + minutes + " min " + seconds + " sec";
}
</script>
<div id="timer"></div>
Hope it helps :)
Change this:
if (count == -1) {
clearInterval(counter);
return;
}
To this:
if (count < 0) {
clearInterval(counter);
localStorage.removeItem('count');
return;
}
Always make your conditions as strict as you can, or you will run into trouble. You don't actually care that it's equal to -1. You care that it's below 0.
In your original code, it stops fine when the page is loaded without localStorage. But at the end, you set the localStorage to -1. When you refresh, you set it to -2 (count - 1) and start the counter going into the negatives. Your condition is never checked against that -1 value which was stored.
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();
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>
I'm creating a countdown timer based on a users input. When the user pauses and resumes, the timer restarts at the initial inputed value and fails to resume from the current interval. I've uploaded the code into Codepen.
http://codepen.io/alivera/pen/JGpvRx
//Timer
var myTimer;
var duration = sessionCounter * 60;
var startTimer = function() {
minutes = parseInt(duration / 60);
seconds = parseInt(duration % 60);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
document.getElementById("clockTimer").innerHTML = minutes + ":" + seconds;
if (--duration < 0) {
document.getElementById("toggleStatus").innerHTML = "<br>Break!";
}
};
//Start Timer
var go = function() {
myTimer = setInterval(startTimer, 1000);
document.getElementById('start').innerHTML = "Stop";
document.getElementById('start').className = "btn btn-danger";
document.getElementById("start").onclick = stop;
};
//Stop Timer
var stop = function() {
clearInterval(myTimer);
document.getElementById('start').innerHTML = "Start";
document.getElementById('start').className = "btn btn-success";
document.getElementById("start").onclick = go;
};
duration.onload = stop();
You're loading the time to count down from from the #clockTimer element:
var sessionCounter = document.getElementById("clockTimer").innerHTML;
This is bad because the contents of that element are changing. Often.
And parseInt on the next line only is only giving you the number before the colon. Your best bet for solving this problem would be storing the current time remaining and the previously set time in separate variables, as I have done below.
Your code was a little difficult to work with, so while correcting the error(s), I ended up almost completely rewriting it.
Here's my version; I'll explain it line-by-line (or section-by-section, or whatever):
First, put all of our elements in to easy-to-use (and type) variables:
var subBreakButton = document.getElementById("subBreakButton"),
breakTimer = document.getElementById("breakTimer"),
addBreakButton = document.getElementById("addBreakButton"),
subSessionButton = document.getElementById("subSessionButton"),
sessionTimer = document.getElementById("sessionTimer"),
addSessionButton = document.getElementById("addSessionButton"),
breakSession = document.getElementById("breakSession"),
clockTimer = document.getElementById("clockTimer"),
These variables are in seconds (thus m * s):
breakLength = 5 * 60, // Minutes to seconds
sessionLength = 25 * 60, // Minutes to seconds
sessionTimeLeft = sessionLength;
Next, a helper method that formats times into a mm:ss ... format:
function timeString (seconds) {
var minutes = parseInt(seconds / 60) + "",
seconds = parseInt(seconds % 60) + "";
if (minutes.length === 1)
minutes = "0" + minutes;
if (seconds.length === 1)
seconds = "0" + seconds;
return minutes + ":" + seconds;
}
Third, event listeners for the plus and minus buttons:
// Event Listeners
addBreakButton.addEventListener("click", function () {
breakLength += 1 * 60;
breakTimer.innerHTML = timeString(breakLength);
});
subBreakButton.addEventListener("click", function () {
breakLength -= 1 * 60;
if (breakLength < 0)
breakLength = 0;
breakTimer.innerHTML = timeString(breakLength);
});
addSessionButton.addEventListener("click", function () {
sessionLength += 1 * 60;
sessionTimer.innerHTML = timeString(sessionLength);
});
subSessionButton.addEventListener("click", function () {
sessionLength -= 1 * 60;
if (sessionLength < 0)
sessionLength = 0;
sessionTimer.innerHTML = timeString(sessionLength);
});
And, the fun part:
// Timer
var myTimer;
function startTimer () {
if (myTimer) // Check to see if a timer was already running, and if so, stop it
stopTimer();
sessionTimeLeft = sessionLength;
myTimer = setInterval(function () {
sessionTimeLeft--;
if (sessionTimeLeft <= 0) {
sessionTimeLeft = 0;
stopTimer();
}
clockTimer.innerHTML = (sessionTimeLeft <= 0? "Break!": timeString(sessionTimeLeft));
}, 1000);
}
function stopTimer () {
clearInterval(myTimer);
myTimer = 0;
}
Lastly, wrappers:
// Start Timer
function go() {
startTimer();
}
//Pause Timer
function stop() {
stopTimer();
}
Codepen: http://codepen.io/anon/pen/ZQjLZE?editors=1010