frontend-challenges
frontend-challenges copied to clipboard
clearAllTimeout
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
clearAllTimeoutso that it clears every pending timeout created bysetTimeout. - 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
setTimeoutorclearTimeoutfunctions 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);
});
});