您可以在倉庫 Github 上找到本文中的所有程式碼。
非同步編程定時器相關的挑戰
有時間限制的緩存
class TimeLimitedCache { constructor() { this._cache = new Map(); } set(key, value, duration) { const found = this._cache.has(key); if (found) { clearTimeout(this._cache.get(key).ref); } this._cache.set(key, { value, ref: setTimeout(() => { this._cache.delete(key); }, duration), }); return found; } get(key) { if (this._cache.has(key)) { return this._cache.get(key); } else { return -1; } } count() { return this._cache.size; } } // Usage example const timeLimitedCache = new TimeLimitedCache(); console.log(timeLimitedCache.set(1, 'first', 1000)); // => false console.log(timeLimitedCache.get(1).value); // => 'first' console.log(timeLimitedCache.count()); // => 1 setTimeout(() => { console.log(timeLimitedCache.count()); // => 0 console.log(timeLimitedCache.get(1)); // => -1 }, 2000);
取消間隔
/** * @param {Function} callback * @param {number} delay * @param {...any} args * @returns {Function} */ function setCancellableInterval(callbackFn, delay, ...args) { const timerId = setInterval(callbackFn, delay, ...args); return () => { clearInterval(timerId); }; } // Usage example let i = 0; // t = 0: const cancel = setCancellableInterval(() => { i++; }, 100); // t = 50: cancel(); // t = 100: i is still 0 because cancel() was called.
取消超時
/** * @param {Function} callbackFn * @param {number} delay * @param {...any} args * @returns {Function} */ function setCancellableTimeout(callbackFn, delay, ...args) { const timerId = setTimeout(callbackFn, delay, ...args); return () => { clearTimeout(timerId); }; } // Usage example let i = 0; // t = 0: const cancel = setCancellableTimeout(() => { i++; }, 100); // t = 50: cancel(); // t = 100: i is still 0 because cancel() was called.
清除所有超時定時器
/** * cancel all timer from window.setTimeout */ const timerQueue = []; const originalSetTimeout = window.setTimeout; window.setTimeout = function (callbackFn, delay, ...args) { const timerId = originalSetTimeout(callbackFn, delay, ...args); timerQueue.push(timerId); return timerId; } function clearAllTimeout() { while (timerQueue.length) { clearTimeout(timerQueue.pop()); } } // Usage example setTimeout(func1, 10000) setTimeout(func2, 10000) setTimeout(func3, 10000) // all 3 functions are scheduled 10 seconds later clearAllTimeout() // all scheduled tasks are cancelled.
去抖動
/** * @param {Function} fn * @param {number} wait * @return {Function} */ function debounce(fn, wait = 0) { let timerId = null; return function (...args) { const context = this; clearTimeout(timerId); timerId = setTimeout(() => { timerId = null; fn.call(context, ...args); }, wait); } } // Usage example let i = 0; function increment() { i += 1; } const debouncedIncrement = debounce(increment, 100); // t = 0: Call debouncedIncrement(). debouncedIncrement(); // i = 0 // t = 50: i is still 0 because 100ms have not passed. // Call debouncedIncrement() again. debouncedIncrement(); // i = 0 // t = 100: i is still 0 because it has only // been 50ms since the last debouncedIncrement() at t = 50. // t = 150: Because 100ms have passed since // the last debouncedIncrement() at t = 50, // increment was invoked and i is now 1 .
風門
/** * @param {Function} fn * @param {number} wait * @return {Function} */ function throttle(fn, wait = 0) { let shouldThrottle = false; return function (...args) { if (shouldThrottle) { return; } shouldThrottle = true; setTimeout(() => { shouldThrottle = false; }, wait); fn.call(this, ...args); } } // Usage example let i = 0; function increment() { i++; } const throttledIncrement = throttle(increment, 100); // t = 0: Call throttledIncrement(). i is now 1. throttledIncrement(); // i = 1 // t = 50: Call throttledIncrement() again. // i is still 1 because 100ms have not passed. throttledIncrement(); // i = 1 // t = 101: Call throttledIncrement() again. i is now 2. // i can be incremented because it has been more than 100ms // since the last throttledIncrement() call at t = 0. throttledIncrement(); // i = 2
重複間隔
const URL = 'https://fastly.picsum.photos/id/0/5000/3333.jpg?hmac=_j6ghY5fCfSD6tvtcV74zXivkJSPIfR9B8w34XeQmvU'; function fetchData(url) { return fetch(url) .then((response) => { if (!response.ok) { throw new Error(`Error: ${response.status}`); } return response.blob(); }) .then((data) => { console.log(data); }) .catch((err) => { console.log(`Error: ${err}`); }); } function repeat(callbackFn, delay, count) { let currentCount = 0; const timerId = setInterval(() => { if (currentCount clearInterval(timerId), } } // Usage example const cancel = repeat(() => fetchData(URL), 2000, 5); setTimeout(() => { cancel.clear(); }, 11000);
可恢復間隔
/** * @param {Function} callbackFn * @param {number} delay * @param {...any} args * @returns {{start: Function, pause: Function, stop: Function}} */ function createResumableInterval(callbackFn, delay, ...args) { let timerId = null; let stopped = false; function clearTimer() { clearInterval(timerId); timerId = null; } function start() { if (stopped || timerId) { return; } callbackFn(...args); timerId = setInterval(callbackFn, delay, ...args); } function pause() { if (stopped) { return; } clearTimer(); } function stop() { stopped = true; clearTimer(); } return { start, pause, stop, }; } // Usage example let i = 0; // t = 0: const interval = createResumableInterval(() => { i++; }, 10); // t = 10: interval.start(); // i is now 1. // t = 20: callback executes and i is now 2. // t = 25: interval.pause(); // t = 30: i remains at 2 because interval.pause() was called. // t = 35: interval.start(); // i is now 3. // t = 45: callback executes and i is now 4. // t = 50: interval.stop(); // i remains at 4.
實作 setInterval()
/** * @param {Function} callbackFn * @param {number} delay * @return {object} */ // use `requestAnimationFrame` function mySetInterval(callbackFn, delay) { let timerId = null; let start = Date.now(); // loop function loop() { const current = Date.now(); if (current - start >= delay) { callbackFn(); start = current; } timerId = requestAnimationFrame(loop); } // run loop loop(); return { clear: () => cancelAnimationFrame(timerId), } } const interval = mySetInterval(() => { console.log('Interval tick'); }, 1000); // cancel setTimeout(() => { interval.clear(); }, 5000); // use `setTimeout` function mySetInterval(callbackFn, delay) { let timerId = null; let start = Date.now(); let count = 0; // loop function loop() { const drift = Date.now() - start - count * delay; count += 1; timerId = setTimeout(() => { callbackFn(); loop(); }, delay - drift); } // run loop loop(); return { clear: () => clearTimeout(timerId), } } const interval = mySetInterval(() => { console.log('Interval tick'); }, 1000); // cancel setTimeout(() => { interval.clear(); }, 5000);
實作 setTimeout()
function setTimeout(callbackFn, delay) { let elapsedTime = 0; const interval = 100; const intervalId = setInterval(() => { elapsedTime += interval; if (elapsedTime >= delay) { clearInterval(intervalId); callbackFn(); } }, interval); } // Usage example mySetTimeout(() => { console.log('This message is displayed after 2 seconds.'); }, 2000);
參考
- 視窗:setTimeout() 方法 - MDN
- 視窗:setInterval() 方法 - MDN
- 視窗:clearInterval() 方法 - MDN
- 視窗:clearTimeout() 方法 - MDN
- 2715。超時取消 - LeetCode
- 2725。間隔取消 - LeetCode
- 2622。有時間限制的快取 - LeetCode
- 2627。反跳 - LeetCode
- 2676。油門 - LeetCode
- 速率限制 - Wikipedia.org
- 28。實作clearAllTimeout() - BFE.dev
- 4.實現基本的throttle() - BFE.dev
- 5.使用前導和尾隨選項實現throttle() - BFE.dev
- 6.實作基本的 debounce() - BFE.dev
- 7.使用前導和尾隨選項實現 debounce() - BFE.dev
- JavaScript 非同步:練習、實作、解決方案 - w3resource
- 偉大的前端
以上是計時器 - JavaScript 挑戰的詳細內容。更多資訊請關注PHP中文網其他相關文章!

Python更適合初學者,學習曲線平緩,語法簡潔;JavaScript適合前端開發,學習曲線較陡,語法靈活。 1.Python語法直觀,適用於數據科學和後端開發。 2.JavaScript靈活,廣泛用於前端和服務器端編程。

Python和JavaScript在社區、庫和資源方面的對比各有優劣。 1)Python社區友好,適合初學者,但前端開發資源不如JavaScript豐富。 2)Python在數據科學和機器學習庫方面強大,JavaScript則在前端開發庫和框架上更勝一籌。 3)兩者的學習資源都豐富,但Python適合從官方文檔開始,JavaScript則以MDNWebDocs為佳。選擇應基於項目需求和個人興趣。

從C/C 轉向JavaScript需要適應動態類型、垃圾回收和異步編程等特點。 1)C/C 是靜態類型語言,需手動管理內存,而JavaScript是動態類型,垃圾回收自動處理。 2)C/C 需編譯成機器碼,JavaScript則為解釋型語言。 3)JavaScript引入閉包、原型鍊和Promise等概念,增強了靈活性和異步編程能力。

不同JavaScript引擎在解析和執行JavaScript代碼時,效果會有所不同,因為每個引擎的實現原理和優化策略各有差異。 1.詞法分析:將源碼轉換為詞法單元。 2.語法分析:生成抽象語法樹。 3.優化和編譯:通過JIT編譯器生成機器碼。 4.執行:運行機器碼。 V8引擎通過即時編譯和隱藏類優化,SpiderMonkey使用類型推斷系統,導致在相同代碼上的性能表現不同。

JavaScript在現實世界中的應用包括服務器端編程、移動應用開發和物聯網控制:1.通過Node.js實現服務器端編程,適用於高並發請求處理。 2.通過ReactNative進行移動應用開發,支持跨平台部署。 3.通過Johnny-Five庫用於物聯網設備控制,適用於硬件交互。

我使用您的日常技術工具構建了功能性的多租戶SaaS應用程序(一個Edtech應用程序),您可以做同樣的事情。 首先,什麼是多租戶SaaS應用程序? 多租戶SaaS應用程序可讓您從唱歌中為多個客戶提供服務

本文展示了與許可證確保的後端的前端集成,並使用Next.js構建功能性Edtech SaaS應用程序。 前端獲取用戶權限以控制UI的可見性並確保API要求遵守角色庫

JavaScript是現代Web開發的核心語言,因其多樣性和靈活性而廣泛應用。 1)前端開發:通過DOM操作和現代框架(如React、Vue.js、Angular)構建動態網頁和單頁面應用。 2)服務器端開發:Node.js利用非阻塞I/O模型處理高並發和實時應用。 3)移動和桌面應用開發:通過ReactNative和Electron實現跨平台開發,提高開發效率。


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

Atom編輯器mac版下載
最受歡迎的的開源編輯器

禪工作室 13.0.1
強大的PHP整合開發環境

SublimeText3漢化版
中文版,非常好用

PhpStorm Mac 版本
最新(2018.2.1 )專業的PHP整合開發工具

SublimeText3 英文版
推薦:為Win版本,支援程式碼提示!