Я использую таймер в JavaScript, я хочу, чтобы, когда мой таймер закончил, он покажет мне предупреждение, но сейчас мой таймер снова перезапускается с того же самого времени. как я могу показать оповещение в моем таймере, когда он закончит.
// 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>
Проблема, с которой вы сталкиваетесь, связана с count
. Вы задали значение 1000
. Таким образом, вам придется подождать 1000 min
до выполнения вашей функции clearInterval(timer)
. Вы можете попробовать следующее:
Таймер перезапускается после перезагрузки страницы
<script type="text/javascript">
// 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 = 6000;
counter = setInterval(timer, 1000); //1000 will run it every 1 second
}
function timer() {
count = count -1;
var seconds = count % 60;
var minutes = Math.floor(count / 60);
var hours = Math.floor(minutes / 60);
minutes %= 60;
if(seconds === 0)
{
clearInterval(counter);
alert("terminated");
}
document.getElementById("timer").innerHTML = seconds + " seconds left to complete this transaction"; // watch for spelling
}
</script>
<div id="timer"></div>
Таймер остается неизменным даже после перезапуска
<script type="text/javascript">
// properties
var count = 0;
var counter = null;
window.onload = function() {
initCounter();
};
function initCounter() {
// get count from localStorage, or set to initial value of 1000
if(!count || count < 0)
{
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);
var seconds = count % 60;
var minutes = Math.floor(count / 60);
var hours = Math.floor(minutes / 60);
minutes %= 60;
if(seconds === 0)
{
clearInterval(counter);
alert("terminated");
}
document.getElementById("timer").innerHTML = seconds + " seconds left to complete this transaction"; // watch for spelling
}
</script>
<div id="timer"></div>
Это не фрагмент, как первый, потому что localstorage
отключен в фрагменте stackoverflow
clearInterval(counter);
, «Возврат» чуть ниже завершает функцию. Поэтому, если у вас есть какие-либо действия, например,alert
, лучшее место перед этимreturn;