frontend-challenges icon indicating copy to clipboard operation
frontend-challenges copied to clipboard

clearAllTimeout

Open jsartisan opened this issue 3 months ago • 0 comments

Info

difficulty: medium
title: clearAllTimeout
type: question
template: javascript
tags: javascript, timers

Question

In JavaScript, clearTimeout is used to cancel a single timeout. Your task is to implement a utility clearAllTimeout that cancels all scheduled timeouts in the current environment.

Requirements

  • Implement clearAllTimeout so that it clears every pending timeout created by setTimeout.
  • Ensure it does not throw errors if no timeouts are scheduled.
  • Works across multiple timeouts.

Example

const id1 = setTimeout(() => console.log('first'), 1000);
const id2 = setTimeout(() => console.log('second'), 2000);

clearAllTimeout();

// Neither "first" nor "second" should be printed

Notes

  • You may assume the environment is Node.js or modern browsers.
  • Do not modify the built-in setTimeout or clearTimeout functions directly.

Template

index.js

/**
 * Clears all pending timeouts
 */
export function clearAllTimeout() {
  // TODO: Implement
}

index.test.js

import { clearAllTimeout } from './index';

describe('clearAllTimeout', () => {
  it('should clear multiple scheduled timeouts', (done) => {
    let called = false;
    setTimeout(() => { called = true; }, 20);
    setTimeout(() => { called = true; }, 30);

    clearAllTimeout();

    setTimeout(() => {
      expect(called).toBe(false);
      done();
    }, 50);
  });

  it('should not throw if no timeouts are scheduled', () => {
    expect(() => clearAllTimeout()).not.toThrow();
  });

  it('should clear timeouts scheduled before execution', (done) => {
    let called = false;
    setTimeout(() => { called = true; }, 40);

    clearAllTimeout();

    setTimeout(() => {
      expect(called).toBe(false);
      done();
    }, 60);
  });
});

jsartisan avatar Sep 05 '25 16:09 jsartisan