Fix bug: Clock can't be stopped when 'Start' clicked while running
This commit is contained in:
parent
e1a3f634a4
commit
d4c23dcf37
2 changed files with 13 additions and 5 deletions
|
@ -39,15 +39,18 @@ 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()`.
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue