」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > JavaScript挑戰:Timer計時器實現攻略

JavaScript挑戰:Timer計時器實現攻略

發佈於2025-04-12
瀏覽:244

Timer - JavaScript Challenges您可以在repo github的这篇文章中找到所有代码。

异步编程计时器相关的挑战


与时间限制的缓存


类TimeLimitedCache { constructor(){ this._cache = new Map(); } set(键,值,持续时间){ const找到= this._cache.has(key); 如果(找到){ clearTimeOut(this._cache.get(key).ref); } this._cache.set(key,{ 价值, 参考:settimeout(()=> { this._cache.delete(key); }, 期间), }); 发现返回; } 获取(键){ if(this._cache.has(key)){ 返回this._cache.get(key); } 别的 { 返回-1; } } 数数() { 返回this._cache.size; } } //用法示例 const timeLimitedCache = new TimeLimitedCache(); console.log(timeLimitedCache.set(1,'first',1000)); // => false console.log(timeLimitedCache.get(1).value); // =>'第一个' console.log(timeLimitedCache.Count()); // => 1 settimeout(()=> { console.log(timeLimitedCache.Count()); // => 0 console.log(timeLimitedCache.get(1)); // => -1 },2000);

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}回调 * @param {number}延迟 * @param {...任何} args * @returns {function} */ 函数setCancellable Interval(callbackfn,delay,... args){ const timerId = setInterval(callbackfn,delay,... args); 返回()=> { clear Interval(TimerId); }; } //用法示例 令i = 0; // t = 0: const cancel = setCancellableInterval((()=> { 我 ; },100); // t = 50: 取消(); // t = 100:我仍然是0,因为cancel()被调用。

/**
 * @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}延迟 * @param {...任何} args * @returns {function} */ 函数setCancellabletimeout(callbackfn,delay,... args){ const TimerId = settimeout(callbackfn,delay,... args); 返回()=> { cleartimeout(timerid); }; } //用法示例 令i = 0; // t = 0: const cancel = setCancellabletimeout(()=> { 我 ; },100); // t = 50: 取消(); // t = 100:我仍然是0,因为cancel()被调用。

/**
 * @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.

/** *从window.settimeout取消所有计时器 */ const timerqueue = []; const OriginalSetTimeOut = window.setTimeOut; window.setTimeout = function(callbackfn,delay,... args){ const timerId = ointersetTimeout(callbackfn,delay,... args); timerqueue.push(timerid); 返回timerid; } 功能ClearallTimeOut(){ while(timerqueue.length){ clearTimeout(timerqueue.pop()); } } //用法示例 settimeout(func1,10000) settimeout(func2,10000) settimeout(func3,10000) //所有3个功能在10秒后安排 clearallTimeOut() //取消所有计划的任务。

/**
 * 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}等待 * @return {function} */ 函数debounce(fn,wait = 0){ 令timerid = null; 返回功能(... args){ const context = this; cleartimeout(timerid); timerId = settimeout(()=> { timerid = null; fn.call(上下文,... args); }, 等待); } } //用法示例 令i = 0; 功能递增(){ i = 1; } const debouncedIncrement = debounce(增量,100); // t = 0:调用debouncedIncrement()。 debouncedIncrement(); // i = 0 // t = 50:我仍然是0,因为100ms尚未通过。 //再次致电debouncedIncrement()。 debouncedIncrement(); // i = 0 // t = 100:我还是0,因为它只有 //自上次debouncedincrement()t = 50以来为50ms。 // t = 150:因为从那以后通过了100ms // t = 50的最后一个debouncedincrement(), //递增被调用,我现在是1。

/**
 * @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}等待 * @return {function} */ 功能节气门(fn,wait = 0){ 让应该throttle = false; 返回功能(... args){ if(应该){ 返回; } 应该throttle = true; settimeout(()=> { 应该throttle = false; }, 等待); fn.call(this,... args); } } //用法示例 令i = 0; 功能递增(){ 我 ; } const throttledIncrement =油门(增量,100); // t = 0:调用thtottledincrement()。我现在是1。 油门固定(); // i = 1 // t = 50:再次调用thtottledincrement()。 //我仍然是1,因为100ms尚未通过。 油门固定(); // i = 1 // t = 101:再次调用thtottledincrement()。我现在2。 //我可以增加,因为它已经超过100ms //自从上次漏油increment()调用t = 0。 油门固定(); // i = 2

/**
 * @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

功能fetchdata(url){ 返回获取(URL) 。然后((响应)=> { if(!wendesp.ok){ 提出新的错误(`错误:$ {wendesp.status}`); } 返回响应blob(); })) 。然后((data)=> { console.log(data); })) .catch(((err)=> { console.log(`错误:$ {err}`); }); } 函数重复(callbackfn,延迟,计数){ 令CurrentCount = 0; const TimerId = setInterval(()=> { if(currentCount clear Interval(timerId), } } //用法示例 const取消=重复(()=> fetchdata(url),2000,5); settimeout(()=> { cancel.clear(); },11000);

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}延迟 * @param {...任何} args * @returns {{start:function,puse:function,stop:function}}} */ 功能createresumable Interval(callbackfn,delay,... args){ 令timerid = null; 让停止= false; 功能clearTimer(){ clear Interval(TimerId); timerid = null; } 函数start(){ 如果(停止|| TimerId){ 返回; } callbackfn(... args); timerId = setInterval(callbackfn,delay,... args); } 功能暂停(){ 如果(停止){ 返回; } cleartimer(); } 函数stop(){ 停止= true; cleartimer(); } 返回 { 开始, 暂停, 停止, }; } //用法示例 令i = 0; // t = 0: const Interval = Createresumable Interval(()=> { 我 ; },10); // t = 10: Interval.start(); //我现在是1。 // t = 20:回调执行,我现在是2。 // t = 25: Interval.pause(); // t = 30:我一直保持2个,因为intervel.pape()被调用。 // t = 35: Interval.start(); //我现在是3。 // t = 45:回调执行,我现在是4。 // t = 50: Interval.stop(); //我留在4岁。

/**
 * @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.

/** * @param {function} callbackfn * @param {number}延迟 * @return {object} */ //使用`requestAnimationFrame' 功能mysetInterval(callbackfn,delay){ 令timerid = null; 让开始= date.now(); // 环形 功能循环(){ const current = date.now(); if(当前 - 开始> =延迟){ callbackfn(); 开始=电流; } timerId = requestAnimationFrame(loop); } //运行循环 环形(); 返回 { clear :()=> cancelAnimationFrame(TimerId), } } const Intertal = mySetInterval(()=> { console.log('Interval Tick'); },1000); // 取消 settimeout(()=> { Interval.Clear(); },5000); //使用`settimeout' 功能mysetInterval(callbackfn,delay){ 令timerid = null; 让开始= date.now(); 让计数= 0; // 环形 功能循环(){ const draft = date.now() - start -count * delay; 计数= 1; timerId = settimeout(()=> { callbackfn(); 环形(); },延迟 - 漂移); } //运行循环 环形(); 返回 { clear :()=> cleartimeout(timerId), } } const Intertal = mySetInterval(()=> { console.log('Interval Tick'); },1000); // 取消 settimeout(()=> { Interval.Clear(); },5000);

/**
 * @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);
[2 令ElapsedTime = 0; const间隔= 100; const interceTalid = setInterval(()=> { ELAPSEDTIME = Interval; if(ElapsedTime> = delay){ clear Interval(Intervalid); callbackfn(); } }, 间隔); } //用法示例 mySetTimeout(()=> { console.log(“此消息将在2秒后显示。”); },2000);

参考
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);

窗口:setInterval()方法-MDN

    窗口:clearInterval()方法-MDN
  • 窗口:cleartimeout()method -mdn
  • 2715。超时取消 - leetcode
  • 2725。间隔取消 - leetcode
  • 2622。带有时间限制的缓存-LeetCode
  • 2627。 debounce -leetcode
  • 2676。油门-LeetCode
  • 28。实现clearallTimeOut()-bfe.dev
  • 4。实现基本油门()-bfe.dev
  • 5。带有领先和尾随选项的实现throttle()-BFE.Dev
  • 6。实施基本debounce()-BFE.DEV
  • 7。用领先和尾随的选项-BFE.DEV
  • JavaScript异步:练习,练习,解决方案-W3Resource
  • Greatfrontend
版本聲明 本文轉載於:https://dev.to/mitchell_cheng/timer-javascript-challenges-25l7?1如有侵犯,請聯繫[email protected]刪除
最新教學 更多>
  • 如何實時捕獲和流媒體以進行聊天機器人命令執行?
    如何實時捕獲和流媒體以進行聊天機器人命令執行?
    在開發能夠執行命令的chatbots的領域中,實時從命令執行實時捕獲Stdout,一個常見的需求是能夠檢索和顯示標準輸出(stdout)在cath cath cant cant cant cant cant cant cant cant interfaces in Chate cant inter...
    程式設計 發佈於2025-05-16
  • 如何使用Java.net.urlConnection和Multipart/form-data編碼使用其他參數上傳文件?
    如何使用Java.net.urlConnection和Multipart/form-data編碼使用其他參數上傳文件?
    使用http request 上傳文件上傳到http server,同時也提交其他參數,java.net.net.urlconnection and Multipart/form-data Encoding是普遍的。 Here's a breakdown of the process:Mu...
    程式設計 發佈於2025-05-16
  • eval()vs. ast.literal_eval():對於用戶輸入,哪個Python函數更安全?
    eval()vs. ast.literal_eval():對於用戶輸入,哪個Python函數更安全?
    稱量()和ast.literal_eval()中的Python Security 在使用用戶輸入時,必須優先確保安全性。強大的Python功能Eval()通常是作為潛在解決方案而出現的,但擔心其潛在風險。 This article delves into the differences betwee...
    程式設計 發佈於2025-05-16
  • CSS強類型語言解析
    CSS強類型語言解析
    您可以通过其强度或弱输入的方式对编程语言进行分类的方式之一。在这里,“键入”意味着是否在编译时已知变量。一个例子是一个场景,将整数(1)添加到包含整数(“ 1”)的字符串: result = 1 "1";包含整数的字符串可能是由带有许多运动部件的复杂逻辑套件无意间生成的。它也可以是故意从单个真理...
    程式設計 發佈於2025-05-16
  • 如何檢查對像是否具有Python中的特定屬性?
    如何檢查對像是否具有Python中的特定屬性?
    方法來確定對象屬性存在尋求一種方法來驗證對像中特定屬性的存在。考慮以下示例,其中嘗試訪問不確定屬性會引起錯誤: >>> a = someClass() >>> A.property Trackback(最近的最新電話): 文件“ ”,第1行, AttributeError: SomeClass...
    程式設計 發佈於2025-05-16
  • 如何限制動態大小的父元素中元素的滾動範圍?
    如何限制動態大小的父元素中元素的滾動範圍?
    在交互式接口中實現垂直滾動元素的CSS高度限制,控制元素的滾動行為對於確保用戶體驗和可訪問性是必不可少的。一種這樣的方案涉及限制動態大小的父元素中元素的滾動範圍。 問題:考慮一個佈局,其中我們具有與用戶垂直滾動一起移動的可滾動地圖div,同時與固定的固定sidebar保持一致。但是,地圖的滾動無限...
    程式設計 發佈於2025-05-16
  • PHP SimpleXML解析帶命名空間冒號的XML方法
    PHP SimpleXML解析帶命名空間冒號的XML方法
    在php 很少,請使用該限制很大,很少有很高。例如:這種技術可確保可以通過遍歷XML樹和使用兒童()方法()方法的XML樹和切換名稱空間來訪問名稱空間內的元素。
    程式設計 發佈於2025-05-16
  • 哪種在JavaScript中聲明多個變量的方法更可維護?
    哪種在JavaScript中聲明多個變量的方法更可維護?
    在JavaScript中聲明多個變量:探索兩個方法在JavaScript中,開發人員經常遇到需要聲明多個變量的需要。對此的兩種常見方法是:在單獨的行上聲明每個變量: 當涉及性能時,這兩種方法本質上都是等效的。但是,可維護性可能會有所不同。 第一個方法被認為更易於維護。每個聲明都是其自己的語句,使...
    程式設計 發佈於2025-05-16
  • Python中嵌套函數與閉包的區別是什麼
    Python中嵌套函數與閉包的區別是什麼
    嵌套函數與python 在python中的嵌套函數不被考慮閉合,因為它們不符合以下要求:不訪問局部範圍scliables to incling scliables在封裝範圍外執行範圍的局部範圍。 make_printer(msg): DEF打印機(): 打印(味精) ...
    程式設計 發佈於2025-05-16
  • 為什麼儘管有效代碼,為什麼在PHP中捕獲輸入?
    為什麼儘管有效代碼,為什麼在PHP中捕獲輸入?
    在php ;?>" method="post">The intention is to capture the input from the text box and display it when the submit button is clicked.但是,輸出...
    程式設計 發佈於2025-05-16
  • 如何在Java的全屏獨家模式下處理用戶輸入?
    如何在Java的全屏獨家模式下處理用戶輸入?
    Handling User Input in Full Screen Exclusive Mode in JavaIntroductionWhen running a Java application in full screen exclusive mode, the usual event ha...
    程式設計 發佈於2025-05-16
  • 如何在Java中正確顯示“ DD/MM/YYYY HH:MM:SS.SS”格式的當前日期和時間?
    如何在Java中正確顯示“ DD/MM/YYYY HH:MM:SS.SS”格式的當前日期和時間?
    如何在“ dd/mm/yyyy hh:mm:mm:ss.ss”格式“ gormat 解決方案:的,請訪問量很大,並應為procectiquiestate的,並在整個代碼上正確格式不多: java.text.simpledateformat; 導入java.util.calendar; 導入java...
    程式設計 發佈於2025-05-16
  • 您如何在Laravel Blade模板中定義變量?
    您如何在Laravel Blade模板中定義變量?
    在Laravel Blade模板中使用Elegance 在blade模板中如何分配變量對於存儲以後使用的數據至關重要。在使用“ {{}}”分配變量的同時,它可能並不總是最優雅的解決方案。 幸運的是,Blade通過@php Directive提供了更優雅的方法: $ old_section =...
    程式設計 發佈於2025-05-16
  • 將圖片浮動到底部右側並環繞文字的技巧
    將圖片浮動到底部右側並環繞文字的技巧
    在Web設計中圍繞在Web設計中,有時可以將圖像浮動到頁面右下角,從而使文本圍繞它纏繞。這可以在有效地展示圖像的同時創建一個吸引人的視覺效果。 css位置在右下角,使用css float and clear properties: img { 浮點:對; ...
    程式設計 發佈於2025-05-16
  • 如何在JavaScript對像中動態設置鍵?
    如何在JavaScript對像中動態設置鍵?
    在嘗試為JavaScript對象創建動態鍵時,如何使用此Syntax jsObj['key' i] = 'example' 1;不工作。正確的方法採用方括號: jsobj ['key''i] ='example'1; 在JavaScript中,數組是一...
    程式設計 發佈於2025-05-16

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3