'why the timer cannot be stopped in JavaScript?
I wanna build a timer calculate from 6s to 0s in a button, and when time shows 0s the button can be clicked and remove the timer. I wrote 2 ways to implement, the 1st worked and the 2nd doesn't worked the timer will continue to negative number. Whats the difference between them?
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<button>reading!(6)</button>
<script>
let b = document.querySelector("button");
b.disabled = 1;
num = 6;
let timer = setInterval(function(){
b.innerHTML="reading("+num+")";
num--;
if(num===0){
clearInterval(timer);
b.innerHTML = "agreed!";
b.disabled = 0;
}
}, 1000);
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<button>reading!(6)</button>
<script>
let b = document.querySelector("button");
b.disabled = 1;
num = 6;
function changeBtn(){
b.innerHTML = "reading("+num+")";
num--;
}
let timer = setInterval(changeBtn, 1000);
if(num === 0){
clearInterval(timer);
b.disabled = 0;
b.innerHTML = "agreed!";
}
</script>
</body>
</html>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
