-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
2ad18cd
commit e975b33
Showing
1 changed file
with
53 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,53 @@ | ||
# 28. implement clearAllTimeout() | ||
|
||
### Problem | ||
|
||
https://bigfrontend.dev/problem/implement-clearAllTimeout | ||
|
||
# | ||
|
||
### Problem Description | ||
|
||
`window.setTimeout()` could be used to schedule some task in the future. | ||
|
||
Could you implement `clearAllTimeout()` to clear all the timers? This might be useful when we want to clear things up before page transition. | ||
|
||
For example | ||
|
||
```js | ||
setTimeout(func1, 10000); | ||
setTimeout(func2, 10000); | ||
setTimeout(func3, 10000); | ||
// all 3 functions are scheduled 10 seconds later | ||
|
||
clearAllTimeout(); | ||
// all scheduled tasks are cancelled. | ||
``` | ||
|
||
**note** | ||
|
||
You need to keep the interface of `window.setTimeout` and `window.clearTimeout` the same, but you could replace them with new logic | ||
|
||
# | ||
|
||
### Solution | ||
|
||
```js | ||
const timerCache = new Set(); | ||
const originalSetTimeout = window.setTimeout; | ||
|
||
window.setTimeout = (cb, delay) => { | ||
const timer = originalSetTimeout(cb, delay); | ||
timerCache.add(timer); | ||
return timer; | ||
}; | ||
|
||
/** | ||
* cancel all timer from window.setTimeout | ||
*/ | ||
function clearAllTimeout() { | ||
for (const timer of timerCache) { | ||
clearTimeout(timer); | ||
} | ||
} | ||
``` |