タイマー - JavaScript の課題
この投稿のすべてのコードは、リポジトリ 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 < count) { callbackFn(); currentCount += 1; } else { clearInterval(timerId); } }, delay); return { clear: () => 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 中国語 Web サイトの他の関連記事を参照してください。

ホットAIツール

Undresser.AI Undress
リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover
写真から衣服を削除するオンライン AI ツール。

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

Video Face Swap
完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

人気の記事

ホットツール

メモ帳++7.3.1
使いやすく無料のコードエディター

SublimeText3 中国語版
中国語版、とても使いやすい

ゼンドスタジオ 13.0.1
強力な PHP 統合開発環境

ドリームウィーバー CS6
ビジュアル Web 開発ツール

SublimeText3 Mac版
神レベルのコード編集ソフト(SublimeText3)

ホットトピック











フロントエンドのサーマルペーパーチケット印刷のためのよくある質問とソリューションフロントエンド開発におけるチケット印刷は、一般的な要件です。しかし、多くの開発者が実装しています...

JavaScriptは現代のWeb開発の基礎であり、その主な機能には、イベント駆動型のプログラミング、動的コンテンツ生成、非同期プログラミングが含まれます。 1)イベント駆動型プログラミングにより、Webページはユーザー操作に応じて動的に変更できます。 2)動的コンテンツ生成により、条件に応じてページコンテンツを調整できます。 3)非同期プログラミングにより、ユーザーインターフェイスがブロックされないようにします。 JavaScriptは、Webインタラクション、シングルページアプリケーション、サーバー側の開発で広く使用されており、ユーザーエクスペリエンスとクロスプラットフォーム開発の柔軟性を大幅に改善しています。

スキルや業界のニーズに応じて、PythonおよびJavaScript開発者には絶対的な給与はありません。 1. Pythonは、データサイエンスと機械学習でさらに支払われる場合があります。 2。JavaScriptは、フロントエンドとフルスタックの開発に大きな需要があり、その給与もかなりです。 3。影響要因には、経験、地理的位置、会社の規模、特定のスキルが含まれます。

この記事の視差スクロールと要素のアニメーション効果の実現に関する議論では、Shiseidoの公式ウェブサイト(https://www.shisido.co.co.jp/sb/wonderland/)と同様の達成方法について説明します。

JavaScriptを学ぶことは難しくありませんが、挑戦的です。 1)変数、データ型、関数などの基本概念を理解します。2)非同期プログラミングをマスターし、イベントループを通じて実装します。 3)DOM操作を使用し、非同期リクエストを処理することを約束します。 4)一般的な間違いを避け、デバッグテクニックを使用します。 5)パフォーマンスを最適化し、ベストプラクティスに従ってください。

JavaScriptの最新トレンドには、TypeScriptの台頭、最新のフレームワークとライブラリの人気、WebAssemblyの適用が含まれます。将来の見通しは、より強力なタイプシステム、サーバー側のJavaScriptの開発、人工知能と機械学習の拡大、およびIoTおよびEDGEコンピューティングの可能性をカバーしています。

同じIDを持つ配列要素をJavaScriptの1つのオブジェクトにマージする方法は?データを処理するとき、私たちはしばしば同じIDを持つ必要性に遭遇します...

Zustand非同期操作のデータの更新問題。 Zustand State Management Libraryを使用する場合、非同期操作を不当にするデータ更新の問題に遭遇することがよくあります。 �...
