Here's a simple html&javascript: When I click on the "start" button, the counter starts, the number displayed being incremented, then when I click on the "start" again, the counter resets and starts all over again. (This is just a practice with setTimeout
and I don't intend to use this as anything.) At first I forgot to stop mainloop and was running another mainloop every time the button is clicked, which resulted in accelerated counting after repeated clicks. I saw this question (javascript - How to stop a setTimeout loop?) and managed to make it work.
And then I changed the javascript slightly. I thought these codes are almost equivalent, but it wasn't --- it no longer worked, multiple mainLoop seemed to be running after clicks. My question: why are these not equivalent? Why isn't the latter working?
Working codes:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div>
<pre id="start" style="background-color:green; width:70px; text-align:center;">Start</pre>
<pre id="count"></pre>
</div>
<script src="main.js"></script>
</body>
</html>
main.js
var counter = 0;
var timer;
function mainLoop(){
counter++;
document.getElementById("count").innerHTML=counter;
timer = setTimeout(mainLoop,100);
}
function start(){
if (timer){
// stop mainLoop that is currently running.
clearTimeout(timer);
}
// and start again.
counter = 0;
mainLoop();
}
document.getElementById("start").addEventListener("click",start);
Then I changed:
var counter = 0;
var timer;
function mainLoop(){
counter++;
document.getElementById("count").innerHTML=counter;
return setTimeout(mainLoop,100); // changed here
}
function start(){
if (timer){
clearTimeout(timer);
}
counter = 0;
timer = mainLoop(); // and here
}
document.getElementById("start").addEventListener("click",start);