Implementing a Custom `clearAllTimers` in JavaScript



Implementing a custom clearAllTimers function involves creating a mechanism to clear all active timeouts and intervals. This can be useful in scenarios where you need to ensure that no timers are left running, such as when cleaning up resources or resetting the application state.


What is clearAllTimers?

A clearAllTimers function clears all active setTimeout and setInterval timers. This is not a built-in JavaScript function, but implementing it can help you understand timer management and memory cleanup.

Real Interview Insights

Interviewers might ask you to:

  • Implement a custom function to clear all active timers.
  • Manage and track timers to ensure they can be cleared effectively.

Implementing Custom clearAllTimers

Here’s an implementation of a custom clearAllTimers function:

const timerManager = (function() {
  const timers = new Set();
 
  function customSetTimeout(callback, delay) {
    const timeoutId = setTimeout(() => {
      callback();
      timers.delete(timeoutId);
    }, delay);
    timers.add(timeoutId);
    return timeoutId;
  }
 
  function customSetInterval(callback, interval) {
    const intervalId = setInterval(callback, interval);
    timers.add(intervalId);
    return intervalId;
  }
 
  function clearAllTimers() {
    timers.forEach(timerId => {
      clearTimeout(timerId);
      clearInterval(timerId);
    });
    timers.clear();
  }
 
  return {
    setTimeout: customSetTimeout,
    setInterval: customSetInterval,
    clearAllTimers,
  };
})();
Explanation:
  • Tracking Timers: Use a Set to store active timer IDs.
  • Custom setTimeout and setInterval: Wrap the native functions to add the timer IDs to the set and remove them upon completion.
  • Clear All Timers: Iterate through the set and clear each timer using both clearTimeout and clearInterval.

Practical Examples

Consider examples with different timers and clearing all timers:

const { setTimeout, setInterval, clearAllTimers } = timerManager;
 
const timeout1 = setTimeout(() => {
  console.log('Timeout 1 executed');
}, 1000);
 
const interval1 = setInterval(() => {
  console.log('Interval 1 executed');
}, 1000);
 
setTimeout(() => {
  console.log('Clearing all timers');
  clearAllTimers();
}, 3000);

Handling Edge Cases

  1. Multiple Timers: Ensure all active timers are cleared, even if new ones are added while clearing.
  2. Mixed Timer Types: Handle both timeouts and intervals correctly.

Enhanced Implementation with Additional Features

const timerManager = (function() {
  const timers = new Set();
 
  function customSetTimeout(callback, delay) {
    const timeoutId = setTimeout(() => {
      callback();
      timers.delete(timeoutId);
    }, delay);
    timers.add(timeoutId);
    return timeoutId;
  }
 
  function customSetInterval(callback, interval) {
    const intervalId = setInterval(callback, interval);
    timers.add(intervalId);
    return intervalId;
  }
 
  function clearAllTimers() {
    timers.forEach(timerId => {
      clearTimeout(timerId);
      clearInterval(timerId);
    });
    timers.clear();
  }
 
  return {
    setTimeout: customSetTimeout,
    setInterval: customSetInterval,
    clearAllTimers,
  };
})();
 
// Example usage with edge cases
const { setTimeout, setInterval, clearAllTimers } = timerManager;
 
const timeout2 = setTimeout(() => {
  console.log('Timeout 2 executed');
}, 1000);
 
const interval2 = setInterval(() => {
  console.log('Interval 2 executed');
}, 500);
 
setTimeout(() => {
  console.log('Clearing all timers');
  clearAllTimers();
}, 2000);
 
setTimeout(() => {
  console.log('Timeout 3 should not execute');
}, 3000);

Use Cases for Custom clearAllTimers

  1. Application Cleanup: Ensuring no timers are left running when cleaning up resources.
  2. State Reset: Resetting the application state and clearing all pending operations.
  3. Debugging: Simplifying debugging by ensuring all timers are cleared during tests.

AI InterviewPrep

Generate interview questions tailored to your background! Includes behavioral, technical, and job-specific questions based on your resume and job descriptions.

Resume Analyzer

Our AI-powered tool reviews your resume, analyzing job descriptions to highlight essential skills and keywords missing from your resume.