Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit d4c23dc

Browse files
committedDec 4, 2020
Fix bug: Clock can't be stopped when 'Start' clicked while running
1 parent e1a3f63 commit d4c23dc

File tree

2 files changed

+13
-5
lines changed

2 files changed

+13
-5
lines changed
 

‎2-ui/1-document/07-modifying-document/10-clock-setinterval/solution.md

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -39,15 +39,18 @@ The clock-managing functions:
3939
```js
4040
let timerId;
4141

42-
function clockStart() { // run the clock
43-
timerId = setInterval(update, 1000);
42+
function clockStart() { // run the clock
43+
if (!timerId) { // only set a new interval if the clock is not running
44+
timerId = setInterval(update, 1000);
45+
}
4446
update(); // (*)
45-
}
4647

4748
function clockStop() {
4849
clearInterval(timerId);
49-
timerId = null;
50+
timerId = null; // (**)
5051
}
5152
```
5253
5354
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.
55+
56+
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()`.

‎2-ui/1-document/07-modifying-document/10-clock-setinterval/solution.view/index.html

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,12 +43,17 @@
4343
}
4444

4545
function clockStart() {
46-
timerId = setInterval(update, 1000);
46+
// set a new interval only if the clock is stopped
47+
// otherwise we would rewrite the timerID reference to the running interval and wouldn't be able to stop the clock ever again
48+
if (!timerId) {
49+
timerId = setInterval(update, 1000);
50+
}
4751
update(); // <-- start right now, don't wait 1 second till the first setInterval works
4852
}
4953

5054
function clockStop() {
5155
clearInterval(timerId);
56+
timerId = null; // <-- clear timerID to indicate that the clock has been stopped, so that it is possible to start it again in clockStart()
5257
}
5358

5459
clockStart();

0 commit comments

Comments
 (0)
Please sign in to comment.