您可以在仓库 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中文网其他相关文章!

JavaScript核心数据类型在浏览器和Node.js中一致,但处理方式和额外类型有所不同。1)全局对象在浏览器中为window,在Node.js中为global。2)Node.js独有Buffer对象,用于处理二进制数据。3)性能和时间处理在两者间也有差异,需根据环境调整代码。

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python和JavaScript的主要区别在于类型系统和应用场景。1.Python使用动态类型,适合科学计算和数据分析。2.JavaScript采用弱类型,广泛用于前端和全栈开发。两者在异步编程和性能优化上各有优势,选择时应根据项目需求决定。

选择Python还是JavaScript取决于项目类型:1)数据科学和自动化任务选择Python;2)前端和全栈开发选择JavaScript。Python因其在数据处理和自动化方面的强大库而备受青睐,而JavaScript则因其在网页交互和全栈开发中的优势而不可或缺。

Python和JavaScript各有优势,选择取决于项目需求和个人偏好。1.Python易学,语法简洁,适用于数据科学和后端开发,但执行速度较慢。2.JavaScript在前端开发中无处不在,异步编程能力强,Node.js使其适用于全栈开发,但语法可能复杂且易出错。

javascriptisnotbuiltoncorc; saninterpretedlanguagethatrunsonenginesoftenwritteninc.1)javascriptwasdesignedAsalightweight,解释edganguageforwebbrowsers.2)Enginesevolvedfromsimpleterterterpretpreterterterpretertestojitcompilerers,典型地提示。

JavaScript可用于前端和后端开发。前端通过DOM操作增强用户体验,后端通过Node.js处理服务器任务。1.前端示例:改变网页文本内容。2.后端示例:创建Node.js服务器。

选择Python还是JavaScript应基于职业发展、学习曲线和生态系统:1)职业发展:Python适合数据科学和后端开发,JavaScript适合前端和全栈开发。2)学习曲线:Python语法简洁,适合初学者;JavaScript语法灵活。3)生态系统:Python有丰富的科学计算库,JavaScript有强大的前端框架。


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

SecLists
SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。

螳螂BT
Mantis是一个易于部署的基于Web的缺陷跟踪工具,用于帮助产品缺陷跟踪。它需要PHP、MySQL和一个Web服务器。请查看我们的演示和托管服务。

ZendStudio 13.5.1 Mac
功能强大的PHP集成开发环境

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