[英]How can I show alert on my timer when timer finished
我在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>
它不是第一個片段,因為在stackoverflow
片段中禁用了localstorage
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.