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

从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实现跨平台开发,提高开发效率。

JavaScript的最新趋势包括TypeScript的崛起、现代框架和库的流行以及WebAssembly的应用。未来前景涵盖更强大的类型系统、服务器端JavaScript的发展、人工智能和机器学习的扩展以及物联网和边缘计算的潜力。

JavaScript是现代Web开发的基石,它的主要功能包括事件驱动编程、动态内容生成和异步编程。1)事件驱动编程允许网页根据用户操作动态变化。2)动态内容生成使得页面内容可以根据条件调整。3)异步编程确保用户界面不被阻塞。JavaScript广泛应用于网页交互、单页面应用和服务器端开发,极大地提升了用户体验和跨平台开发的灵活性。


热AI工具

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

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

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

AI Hentai Generator
免费生成ai无尽的。

热门文章

热工具

PhpStorm Mac 版本
最新(2018.2.1 )专业的PHP集成开发工具

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

WebStorm Mac版
好用的JavaScript开发工具

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

MinGW - 适用于 Windows 的极简 GNU
这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。