From e975b3340427dbcacc13ea3de159fda5e31b7817 Mon Sep 17 00:00:00 2001 From: Shaban-Eissa Date: Mon, 3 Jun 2024 20:57:58 +0300 Subject: [PATCH] feat: implement clearAllTimeout --- 28.implement-clearAllTimeout.md | 53 +++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 28.implement-clearAllTimeout.md diff --git a/28.implement-clearAllTimeout.md b/28.implement-clearAllTimeout.md new file mode 100644 index 0000000..b409a4f --- /dev/null +++ b/28.implement-clearAllTimeout.md @@ -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); + } +} +```