"यदि कोई कर्मचारी अपना काम अच्छी तरह से करना चाहता है, तो उसे पहले अपने औजारों को तेज करना होगा।" - कन्फ्यूशियस, "द एनालेक्ट्स ऑफ कन्फ्यूशियस। लू लिंगगोंग"
मुखपृष्ठ > प्रोग्रामिंग > जावास्क्रिप्ट चुनौती: टाइमर टाइमर कार्यान्वयन गाइड

जावास्क्रिप्ट चुनौती: टाइमर टाइमर कार्यान्वयन गाइड

2025-04-12 को पोस्ट किया गया
ब्राउज़ करें:724

]

Timer - JavaScript Challenges Async प्रोग्रामिंग टाइमर संबंधित चुनौतियां

समय सीमा के साथ कैश

वर्ग समय -समय पर { कंस्ट्रक्टर () { this._cache = नया मानचित्र (); } सेट (कुंजी, मूल्य, अवधि) { const मिला = this._cache.has (कुंजी); अगर मिल गया) { ClearTimeout (this._cache.get (कुंजी) .ref); } this._cache.set (कुंजी, { कीमत, Ref: SetTimeOut () => { this._cache.delete (कुंजी); }, अवधि), }); वापसी मिली; } चाबी देना) { if (this._cache.has (कुंजी)) { This._cache.get (कुंजी) लौटें; } अन्य { वापसी -1; } } गिनती करना() { इसे लौटाएं ।_cache.size; } } // उपयोग उदाहरण const timeLimitedCache = new TimeLimitedCache (); Console.log (timelimitedCache.set (1, 'पहला', 1000)); // => गलत Console.log (timeLimitedCache.get (1) .value); // => 'पहला' कंसोल.लॉग (timeLimitedCache.count ()); // => 1 setTimeout () => { कंसोल.लॉग (timeLimitedCache.count ()); // => 0 कंसोल.लॉग (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} 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.

debounce

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

दोहराना अंतराल

] फ़ंक्शन fetchData (URL) { लौटा (URL) .then ((प्रतिक्रिया) => { if (response.ok) { नई त्रुटि फेंक दो (`त्रुटि: $ {response.status}`); } रिटर्न रिस्पांस.ब्लोब (); }) .then ((डेटा) => { कंसोल.लॉग (डेटा); }) .catch ((गलत) => { Console.log (`त्रुटि: $ {err}`); }); } फ़ंक्शन रिपीट (CallBackFn, देरी, गिनती) { चलो currentCount = 0; const timerid = setInterval (() => {{ if (currentCount clearnterval (टाइमरड), } } // उपयोग उदाहरण const रद्द = दोहराना () => fetchData (url), 2000, 5); setTimeout () => { रद्द करें। क्लियर (); }, 11000);
/**
 * @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

रिज्यूमेबल अंतराल

/** * @param {फ़ंक्शन} CallBackFn * @param {नंबर} देरी * @param {... कोई भी} args * @returns {{START: फ़ंक्शन, पॉज़: फ़ंक्शन, स्टॉप: फ़ंक्शन}} * फ़ंक्शन createresumableInterval (Callbackfn, देरी, ... args) { लेट टाइमर = नल; बंद कर दिया = गलत; समारोह Cleartimer () { Clearnterval (टाइमरड); टाइमरड = नल; } फ़ंक्शन स्टार्ट () { if (बंद कर दिया || टाइमरड) { वापस करना; } Callbackfn (... args); timerid = setInterval (Callbackfn, देरी, ... args); } फ़ंक्शन पॉज़ () { if (बंद) { वापस करना; } Cleartimer (); } फंक्शन स्टॉप () { रोका गया = सच; Cleartimer (); } वापस करना { शुरू करना, विराम, रुकना, }; } // उपयोग उदाहरण आइए मैं = 0; // t = 0: const अंतराल = createresumableInterval () => {{ मैं ; }, 10); // t = 10: interval.start (); // मैं अब 1 है। // t = 20: कॉलबैक निष्पादित करता है और मैं अब 2 है। // t = 25: interval.pause (); // t = 30: मैं 2 पर रहता है क्योंकि interval.pause () कहा जाता था। // t = 35: interval.start (); // मैं अब 3 है। // t = 45: कॉलबैक निष्पादित करता है और मैं अब 4 है। // t = 50: interval.stop (); // मैं 4 पर रहता है।
/**
 * @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

SetInterval को लागू करें ()

/** * @param {फ़ंक्शन} CallBackFn * @param {नंबर} देरी * @return {ऑब्जेक्ट} * // `` `equestanimationframe` का उपयोग करें फ़ंक्शन mysetInterval (CallBackfn, देरी) { लेट टाइमर = नल; शुरू करें = दिनांक। अब (); // कुंडली फ़ंक्शन लूप () { const current = date.now (); if (वर्तमान - प्रारंभ> = देरी) { callbackfn (); प्रारंभ = वर्तमान; } TimerId = requestImationFrame (लूप); } // रन लूप कुंडली(); वापस करना { स्पष्ट: () => cancelanimationFrame (टाइमरड), } } const अंतराल = mysetInterval (() => {{ कंसोल.लॉग ('अंतराल टिक'); }, 1000); // रद्द करना setTimeout () => { interval.clear (); }, 5000); // `SetTimeOut` का उपयोग करें फ़ंक्शन mysetInterval (CallBackfn, देरी) { लेट टाइमर = नल; शुरू करें = दिनांक। अब (); गिनती = 0; // कुंडली फ़ंक्शन लूप () { const drift = date.now () - प्रारंभ - गिनती * देरी; गिनती = 1; timerid = setTimeout (() => { callbackfn (); कुंडली(); }, देरी - बहाव); } // रन लूप कुंडली(); वापस करना { स्पष्ट: () => ClearTimeout (टाइमरड), } } const अंतराल = mysetInterval (() => {{ कंसोल.लॉग ('अंतराल टिक'); }, 1000); // रद्द करना setTimeout () => { interval.clear (); }, 5000);
/**
 * @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

SETTIMEOUT () को लागू करें

] बीटेडटाइम = 0; कास्ट अंतराल = 100; const intervalid = setInterval () => { बीप्डटाइम = अंतराल; if (elapsedtime> = देरी) { Clearnterval (अंतराल); callbackfn (); } }, अंतराल); } // उपयोग उदाहरण MySettimeout () => { कंसोल.लॉग ('यह संदेश 2 सेकंड के बाद प्रदर्शित होता है।'); }, 2000);

/**
 * @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);
संदर्भ

] ] ]

विंडो: क्लियरटाइमआउट () विधि - mdn
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);
2715। टाइमआउट रद्दीकरण - लेटकोड

2725। अंतराल रद्द करना - लेटकोड

    2622। समय सीमा के साथ कैश - लेटकोड
  • 2627। DEBANCE - LEETCODE
  • 2676। थ्रॉटल - लेटकोड
  • दर सीमित - wikipedia.org
  • 28। Clearlltimeout () - bfe.dev
  • लागू करें
  • ४। बुनियादी थ्रॉटल को लागू करें () - bfe.dev
  • ५। अग्रणी और अनुगामी विकल्प के साथ थ्रॉटल () को लागू करें - bfe.dev
  • 6। बुनियादी बहस को लागू करें () - bfe.dev
  • ]। अग्रणी बहस () अग्रणी और अनुगामी विकल्प के साथ- bfe.dev
  • ]
  • ग्रेटफ्रंटेंड
विज्ञप्ति वक्तव्य इस लेख को पुन: प्रस्तुत किया गया है: https://dev.to/mitchell_cheng/timer-javascript-challenges-25l7?1 यदि कोई उल्लंघन है, तो कृपया इसे हटाने के लिए [email protected] पर संपर्क करें।
नवीनतम ट्यूटोरियल अधिक>

चीनी भाषा का अध्ययन करें

अस्वीकरण: उपलब्ध कराए गए सभी संसाधन आंशिक रूप से इंटरनेट से हैं। यदि आपके कॉपीराइट या अन्य अधिकारों और हितों का कोई उल्लंघन होता है, तो कृपया विस्तृत कारण बताएं और कॉपीराइट या अधिकारों और हितों का प्रमाण प्रदान करें और फिर इसे ईमेल पर भेजें: [email protected] हम इसे आपके लिए यथाशीघ्र संभालेंगे।

Copyright© 2022 湘ICP备2022001581号-3