I am using timer in JavaScript, I want that when my timer is finish it show me alert but right now my timer restart again with same time can any one guide me. how can I show alert in my timer when it finish.
// properties
var count = 0;
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;
document.getElementById("timer").innerHTML = seconds + " seconds left to complete this transaction"; // watch for spelling
}
<div id="timer"></div>
The issue you are facing is related to
count
. You set it to1000
. So you will have to wait1000 min
before your functionclearInterval(timer)
is executed. You can try the following:Timer restarts after reloading the page
Timer remains unchanged even after restart
It is not a snippet as the first one, because
localstorage
are disabled in snippet ofstackoverflow