'How to alert when count down is over
Please help me! I make some simple app for bike renting in local storage. How to alert("Expired") when counter reach zero. When i put alert inside setInterval method, i have repeating alert evry second.
var interval = 5000;
function reset() {
localStorage.endTime = +new Date + interval;
}
if (!localStorage.endTime) {
reset();
}
var remaining = localStorage.endTime - new Date;
setInterval(brojanje, 100)
function brojanje() {
if (remaining > 0) {
$('#timer').text(Math.floor(remaining / 1000));
} else {
return;
}
}
<div Time remaining: <span id="timer">
</span>
</div>
<button onclick="reset()">Click me</button>
Solution 1:[1]
You need to stop your timer using clearInterval function.
var interval = setInterval(brojanje, 100);
function brojanje() {
if (remaining > 0) {
$('#timer').text(Math.floor(remaining / 1000));
} else {
console.log('Alert and kill timer');
alert('STOP!');
clearInterval(interval);
}
}
Solution 2:[2]
Here's a version I worked on. I removed the use of jquery too.
<script>
let duration = 5000
let end_time = 0
let the_interval
function reset () {
end_time = Date.now() + duration
localStorage.endTime = end_time
}
function start_interval () {
clearInterval(the_interval)
let timer = document.querySelector("#timer")
the_interval = setInterval(function () {
let remaining = end_time - Date.now()
if (remaining <= 0) {
clearInterval(the_interval)
return
}
timer.textContent = Math.floor(remaining / 1000)
}, 100)
}
window.onload = function () {
document.querySelector("#reset_button").addEventListener("click", function () {
reset()
start_interval()
})
end_time = parseInt(localStorage.endTime)
start_interval()
}
</script>
<span>Time remaining:</span> <span id="timer"></span></div>
<button id="reset_button">Click me</button>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Devesh |
| Solution 2 | madprops |
