Merge pull request #2347 from PGlivicky/fix-clock-setinterval-solution

Fix bug in the 'colored clock with setInterval' task's solution
This commit is contained in:
Ilya Kantor 2020-12-05 18:07:08 +03:00 committed by GitHub
commit f274f4d1f9
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 13 additions and 4 deletions

View file

@ -39,15 +39,19 @@ The clock-managing functions:
```js
let timerId;
function clockStart() { // run the clock
timerId = setInterval(update, 1000);
function clockStart() { // run the clock
if (!timerId) { // only set a new interval if the clock is not running
timerId = setInterval(update, 1000);
}
update(); // (*)
}
function clockStop() {
clearInterval(timerId);
timerId = null;
timerId = null; // (**)
}
```
Please note that the call to `update()` is not only scheduled in `clockStart()`, but immediately run in the line `(*)`. Otherwise the visitor would have to wait till the first execution of `setInterval`. And the clock would be empty till then.
Also it is important to set a new interval in `clockStart()` only when the clock is not running. Otherways clicking the start button several times would set multiple concurrent intervals. Even worse - we would only keep the `timerID` of the last interval, losing references to all others. Then we wouldn't be able to stop the clock ever again! Note that we need to clear the `timerID` when the clock is stopped in the line `(**)`, so that it can be started again by running `clockStart()`.

View file

@ -43,12 +43,17 @@
}
function clockStart() {
timerId = setInterval(update, 1000);
// set a new interval only if the clock is stopped
// otherwise we would rewrite the timerID reference to the running interval and wouldn't be able to stop the clock ever again
if (!timerId) {
timerId = setInterval(update, 1000);
}
update(); // <-- start right now, don't wait 1 second till the first setInterval works
}
function clockStop() {
clearInterval(timerId);
timerId = null; // <-- clear timerID to indicate that the clock has been stopped, so that it is possible to start it again in clockStart()
}
clockStart();