Anda boleh menemui semua kod dalam siaran ini di repo Github.
Cabaran berkaitan pemasa pengaturcaraan Async
Cache dengan had masa
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);
Batalkan selang waktu
/** * @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.
Batalkan tamat masa
/** * @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.
Kosongkan semua pemasa tamat masa
/** * 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.
Debounce
/** * @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 .
Pendikit
/** * @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
Ulang selang
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);
Selang boleh disambung semula
/** * @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.
Laksanakan 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);
Laksanakan 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);
Rujukan
- Tetingkap: kaedah setTimeout() - MDN
- Tetingkap: kaedah setInterval() - MDN
- Tetingkap: kaedah clearInterval() - MDN
- Tetingkap: kaedah clearTimeout() - MDN
- 2715. Pembatalan Tamat Masa - LeetCode
- 2725. Pembatalan Selang - LeetCode
- 2622. Cache Dengan Had Masa - LeetCode
- 2627. Debounce - LeetCode
- 2676. Pendikit - LeetCode
- Penghadan kadar - Wikipedia.org
- 28. laksana clearAllTimeout() - BFE.dev
- 4. laksanakan pendikit asas() - BFE.dev
- 5. laksanakan pendikit() dengan pilihan mendahului & mengekori - BFE.dev
- 6. laksanakan debounce() asas - BFE.dev
- 7. laksanakan debounce() dengan pilihan mendahului & mengekor- BFE.dev
- JavaScript Asynchronous: Latihan, Amalan, Penyelesaian - w3resource
- GreatFrontEnd
Atas ialah kandungan terperinci Pemasa - Cabaran JavaScript. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Alat AI Hot

Undress AI Tool
Gambar buka pakaian secara percuma

Undresser.AI Undress
Apl berkuasa AI untuk mencipta foto bogel yang realistik

AI Clothes Remover
Alat AI dalam talian untuk mengeluarkan pakaian daripada foto.

Clothoff.io
Penyingkiran pakaian AI

Video Face Swap
Tukar muka dalam mana-mana video dengan mudah menggunakan alat tukar muka AI percuma kami!

Artikel Panas

Alat panas

Notepad++7.3.1
Editor kod yang mudah digunakan dan percuma

SublimeText3 versi Cina
Versi Cina, sangat mudah digunakan

Hantar Studio 13.0.1
Persekitaran pembangunan bersepadu PHP yang berkuasa

Dreamweaver CS6
Alat pembangunan web visual

SublimeText3 versi Mac
Perisian penyuntingan kod peringkat Tuhan (SublimeText3)

Topik panas

Java dan JavaScript adalah bahasa pengaturcaraan yang berbeza, masing -masing sesuai untuk senario aplikasi yang berbeza. Java digunakan untuk pembangunan aplikasi perusahaan dan mudah alih yang besar, sementara JavaScript digunakan terutamanya untuk pembangunan laman web.

JavaScriptcommentsareessentialformaintaining,reading,andguidingcodeexecution.1)Single-linecommentsareusedforquickexplanations.2)Multi-linecommentsexplaincomplexlogicorprovidedetaileddocumentation.3)Inlinecommentsclarifyspecificpartsofcode.Bestpractic

Titik berikut harus diperhatikan apabila tarikh pemprosesan dan masa di JavaScript: 1. Terdapat banyak cara untuk membuat objek tarikh. Adalah disyorkan untuk menggunakan rentetan format ISO untuk memastikan keserasian; 2. Dapatkan dan tetapkan maklumat masa boleh diperoleh dan tetapkan kaedah, dan ambil perhatian bahawa bulan bermula dari 0; 3. Tarikh pemformatan secara manual memerlukan rentetan, dan perpustakaan pihak ketiga juga boleh digunakan; 4. Adalah disyorkan untuk menggunakan perpustakaan yang menyokong zon masa, seperti Luxon. Menguasai perkara -perkara utama ini secara berkesan dapat mengelakkan kesilapan yang sama.

PlacingtagsatthebottomofablogpostorwebpageservespracticalpurposesforSEO,userexperience,anddesign.1.IthelpswithSEObyallowingsearchenginestoaccesskeyword-relevanttagswithoutclutteringthemaincontent.2.Itimprovesuserexperiencebykeepingthefocusonthearticl

JavaScriptispreferredforwebdevelopment, whersjavaisbetterforlarge-scalebackendsystemsandandroidapps.1) javascriptexcelsinceleatinginteractiveWebexperienceswithitsdynamicnatureanddommanipulation.2) javaoffersstrongyblectionandobjection

JavascripthassevenfundamentalDatypes: nombor, rentetan, boolean, undefined, null, objek, andsymbol.1) numberuseadouble-precisionformat, bergunaforwidevaluangesbutbecautiouswithfloating-pointarithmetic.2)

Penangkapan dan gelembung acara adalah dua peringkat penyebaran acara di Dom. Tangkap adalah dari lapisan atas ke elemen sasaran, dan gelembung adalah dari elemen sasaran ke lapisan atas. 1. Penangkapan acara dilaksanakan dengan menetapkan parameter useCapture addeventlistener kepada benar; 2. Bubble acara adalah tingkah laku lalai, useCapture ditetapkan kepada palsu atau ditinggalkan; 3. Penyebaran acara boleh digunakan untuk mencegah penyebaran acara; 4. Acara menggelegak menyokong delegasi acara untuk meningkatkan kecekapan pemprosesan kandungan dinamik; 5. Penangkapan boleh digunakan untuk memintas peristiwa terlebih dahulu, seperti pemprosesan pembalakan atau ralat. Memahami kedua -dua fasa ini membantu mengawal masa dan bagaimana JavaScript bertindak balas terhadap operasi pengguna.

Java dan JavaScript adalah bahasa pengaturcaraan yang berbeza. 1.Java adalah bahasa yang ditaip dan disusun secara statik, sesuai untuk aplikasi perusahaan dan sistem besar. 2. JavaScript adalah jenis dinamik dan bahasa yang ditafsirkan, terutamanya digunakan untuk interaksi web dan pembangunan front-end.
