Skip to main content

Scheduling / Timing

Advanced Functions: Scheduling: setTimeout / setInterval



What are the two most common JavaScript methods used for scheduling a call?

View Answer:
Interview Response: The two most common JavaScript methods for scheduling a call are setTimeout() for single delayed execution and setInterval() for repeated execution at specified intervals.

Technical Response: There are two commonly used methods for scheduling calls in JavaScript, including the setTimeout and setInterval methods. setTimeout allows us to run a function once after the interval of time. setInterval allows us to run a function repeatedly, starting after the interval of time, then repeating continuously at that interval. Both methods are helpful when you need to schedule specific events or actions in JavaScript. These methods don’t get included in the JavaScript specification. However, most settings have an internal scheduler, and these methods are available. All browsers, as well as Node.js, support them. Both methods are part of the WindowOrGlobalScope interface as a specification.

Code Example:

setTimeout(function() {
// Code to be executed after the delay
}, 3000); // Delay of 3000 milliseconds (3 seconds)

setInterval(function() {
// Code to be executed repeatedly at the specified interval
}, 5000); // Interval of 5000 milliseconds (5 seconds)

What is the difference between setTimeout and setInterval in JavaScript?

View Answer:
Interview Response: The setTimeout method schedules a single function execution after a specified delay, while setInterval method schedules a function to execute repeatedly at specified intervals, enabling continuous updates or recurring tasks.

Can you explain the function of the setTimeout() method?

View Answer:
Interview Response: The setTimeout method schedules a single function execution after a specified delay, while setInterval method schedules a function to execute repeatedly at specified intervals, enabling continuous updates or recurring tasks.

Technical Response: The setTimeout() function of the WindowOrWorkerGlobalScope mixin (the Window. setTimeout()) creates a timer that, when it expires, executes a function or provides a piece of code. The func/code, delay (optional), and several optional arguments are all parameters. The func / code must be present, but the delay and optional arguments are not. If the delay option is not specified, a value of 0 is used, which means that the event is executed immediately, or more precisely, the following event cycle. You should note that the actual delay may be greater than anticipated in any instance. The timerID returned by setTimeout() is a positive integer value that identifies the timer generated by the call; this value may be provided to clearTimeout() to cancel the timeout.

Code Example:

Syntax: let timerId = setTimeout(func|code, [delay], [arg1], [arg2], ...);

function sayHi() {
console.log('Hello');
}

setTimeout(sayHi, 1000);

// setTimeout without arguments:

function sayHi(phrase, who) {
console.log(phrase + ', ' + who);
}

setTimeout(sayHi, 1000, 'Hello', 'John'); // Hello, John

// Arrow function implementation
setTimeout(() => console.log('Hello'), 1000);

note

We can use the clearTimeout method to clear setTimeout in our code.


How do you cancel a scheduled setTimeout call?

View Answer:
Interview Response: To cancel a scheduled setTimeout call, you can use the clearTimeout() method, passing the timeout identifier returned by the corresponding setTimeout() invocation as its argument.

Code Example:

// Schedule a function to be executed after 5 seconds
var timeoutId = setTimeout(function() {
console.log("Scheduled function executed.");
}, 5000);

// Cancel the scheduled setTimeout call
clearTimeout(timeoutId);

Can you explain the function of the clearTimeout() method?

View Answer:
Interview Response: The clearTimeout() method cancels a previously scheduled setTimeout() call, preventing the associated function or code snippet from executing after the specified delay.

Code Example:

let timerID = setTimeout(() => console.log('never happens'), 1000);
console.log(timerID); // timer identifier

clearTimeout(timerID);
console.log(timerID); // same identifier (does not become null after canceling)
note

It's worth noting that the pool of IDs used by setTimeout() and setInterval() are shared, which means you can technically use clearTimeout() and clearInterval() interchangeably. However, for clarity, you should avoid doing so.


Can you explain the function of the setInterval() method?

View Answer:
Interview Response: The setInterval() method schedules a function or code snippet to execute repeatedly at specified intervals, measured in milliseconds, allowing for recurring tasks or continuous updates.

Technical Response: The setInterval method has the same syntax as setTimeout. Parameters include the func/code, delay (optional), and some optional arguments. The func / code is required, but delay and optional arguments are not. The time, in milliseconds (thousandths of a second), the timer should delay in between executions of the specified function or code. See Delay restrictions below for details on the acceptable range of delay values. All arguments have the same meaning. But unlike setTimeout it runs the function not only once but regularly after the given interval of time. To stop further calls, we should call clearInterval(timerId).

Code Example:

Syntax: let timerId = setInterval(func|code, [delay], [arg1], [arg2], ...);

// repeat with the interval of 2 seconds
let timerId = setInterval(() => console.log('tick'), 2000);

// after 5 seconds stop
setTimeout(() => {
clearInterval(timerId);
console.log('stop');
}, 5000);

How does garbage collection work with the setInterval and setTimeout callbacks?

View Answer:
Interview Response: Garbage collection in JavaScript retains setInterval and setTimeout callbacks until they execute or are cleared, preventing memory leaks and ensuring proper execution of scheduled tasks.

Technical Response: When a function gets passed in setInterval/setTimeout, an internal reference is created to it and saved in the scheduler. It prevents the function from being garbage collected, even if there are no other references to it. For setInterval the function stays in memory until clearInterval gets called. There is a side-effect. A function references the outer lexical environment, so, while it lives, outer variables live too. They may take much more memory than the function itself. So, when we do not need the scheduled function anymore, it is better to cancel it, even if it is small.

Code Example:

// the function stays in memory until the scheduler calls it

// Example using setInterval
function doRepeatedTask() {
console.log("Executing repeated task...");
}

// Schedule a repeated task every 1 second
var intervalId = setInterval(doRepeatedTask, 1000);

// Clear the interval after 5 seconds
setTimeout(function() {
clearInterval(intervalId);
console.log("Interval cleared after 5 seconds.");
}, 5000);

note

There is a side-effect. A function references the outer lexical environment, so, while it lives, outer variables live too, and they may take much more memory than the function itself. So, when we do not need the scheduled function anymore, it is better to cancel it, even if it's minimal.


How does zero delay setTimeout execute in JavaScript?

View Answer:
Interview Response: A zero delay setTimeout defers the execution of the callback function until the current call stack is clear, effectively making it asynchronous and allowing other tasks to run first.

Code Example:

setTimeout(() => console.log('JavaScript!')); // returns second

console.log('Hello'); // returns first
note

There are also advanced browser-related use cases of the zero-delay timeout, such as splitting CPU-hungry tasks.


How do you cancel a scheduled setInterval() call?

View Answer:
Interview Response: To cancel a scheduled setInterval call, we invoke the clearInterval() method with the interval identifier as its argument, which is the value returned by the corresponding setInterval() call that initiated the repetition.

Code Example:

// Schedule a repeated task every 1 second
var intervalId = setInterval(function() {
console.log("Executing repeated task...");
}, 1000);

// Cancel the scheduled interval after 5 seconds
setTimeout(function() {
clearInterval(intervalId);
console.log("Interval canceled after 5 seconds.");
}, 5000);

How can you create a recursive setTimeout to mimic setInterval behavior?

View Answer:
Interview Response: We can create a recursive setTimeout by scheduling a new setTimeout call within the callback function itself, ensuring it executes repeatedly with the desired delay, thereby mimicking setInterval behavior.

Code Example:

function recursiveSetTimeout(callback, delay) {
setTimeout(function() {
callback();
recursiveSetTimeout(callback, delay);
}, delay);
}

// Example usage
recursiveSetTimeout(function() {
console.log('Recursive setTimeout example');
}, 1000);

In the above example, the recursiveSetTimeout function schedules the execution of the provided callback function repeatedly with the specified delay, effectively mimicking the behavior of setInterval. Each iteration schedules the next execution by calling recursiveSetTimeout recursively inside the callback function.


What is the minimum delay for setTimeout and setInterval in modern browsers?

View Answer:
Interview Response: The minimum delay for setTimeout and setInterval in modern browsers is four milliseconds, after the 5th call, due to browser-imposed limitations on timers.

Code Example:

// Minimum delay for setTimeout
setTimeout(function() {
console.log("Minimum delay reached for setTimeout");
}, 4);

// Minimum delay for setInterval
var counter = 0;
var intervalId = setInterval(function() {
console.log("Minimum delay reached for setInterval");
counter++;
if (counter === 5) {
clearInterval(intervalId);
console.log("Interval cleared after 5 iterations.");
}
}, 4);

How can you throttle or debounce functions using setTimeout?

View Answer:
Interview Response: To throttle or debounce functions using setTimeout, wrap the original function in a higher-order function that uses setTimeout to delay the function call, ensuring a minimum delay between successive calls, reducing the frequency of execution.

Simple Code Example:

1. Debounce Example

function debounce(func, timeout = 300){
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => { func.apply(this, args); }, timeout);
};
}
function saveInput(){
console.log('Saving data');
}
const processChange = debounce(() => saveInput());

2. Throttle Example

function throttle(callback, delay = 1000) {
let shouldWait = false;

return (...args) => {
if (shouldWait) return;

callback(...args);
shouldWait = true;
setTimeout(() => {
shouldWait = false;
}, delay);
};
}

How does JavaScript's event loop work with setTimeout and setInterval?

View Answer:
Interview Response: The setTimeout and setInterval methods are added to the message queue by the event loop after the specified delay, allowing the JavaScript engine to execute other tasks while waiting for the timer to expire.

What is the impact of using setInterval on browser performance?

View Answer:
Interview Response: Using setInterval can cause performance issues, especially if the interval duration is too short, leading to higher CPU and memory usage and reduced user experience, especially on low-end devices.

How can you handle errors in setTimeout and setInterval callbacks?

View Answer:
Interview Response: We can wrap the callback function in a try-catch block to handle errors in setTimeout and setInterval callbacks. Alternatively, utilize error handling mechanisms like window.onerror or try-catch in the outer scope of the callback.

Code Example:

setTimeout(() => {
try {
let code = null;
console.log(code.hello); // this will fail
} catch (error) {
// Handle the error
console.log(error.name); // TypeError
console.log(error.stack); // TypeError: Cannot read properties of null (reading 'hello') at <anonymous>:4:24
}
}, 4);

How do setTimeout and setInterval interact with Promises and async/await?

View Answer:
Interview Response: When used in conjunction with Promises and async/await, the setTimeout and setInterval methods return a Promise or an Async Function, respectively, allowing for more precise control over the timing of code execution.

Code Example:

function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}

async function myFunction() {
console.log('Before delay');
await delay(2000); // Wait for 2 seconds
console.log('After delay');
}

myFunction();

Can you explain the use cases of requestAnimationFrame and its advantages over setInterval for animations?

View Answer:
Interview Response: The requestAnimationFrame method is designed for animation use cases, ensuring smooth, optimized performance at a consistent frame rate. It reduces CPU and GPU usage, improves battery life, and avoids flickering and jank associated with setInterval.

Code Example:

const element = document.getElementById('animationElement');
let start;

function step(timestamp) {
if (start === undefined) start = timestamp;
const elapsed = timestamp - start;

// `Math.min()` is used here to make sure that the element stops at exactly 200px.
element.style.transform =
'translateX(' + Math.min(0.1 * elapsed, 200) + 'px)';

if (elapsed < 2000) {
// Stop the animation after 2 seconds
window.requestAnimationFrame(step);
}
}

window.requestAnimationFrame(step);

What are the differences between using setTimeout and requestIdleCallback for scheduling low-priority tasks?

View Answer:
Interview Response: setTimeout schedules tasks to run after a specified delay, while requestIdleCallback schedules tasks to run during idle periods when the browser has free CPU time, optimizing for performance and user experience.

Code Example:

function myCallback() {
// do something when the browser is idle
}

requestIdleCallback(myCallback);

How do you measure the elapsed time between two events in JavaScript?

View Answer:
Interview Response: To measure elapsed time between two events in JavaScript, store the current timestamp using the 'Date.now()' or 'performance.now()' methods and subtract it from the timestamp at the end of the event.

Code Example:

// Capture the start time
const startTime = performance.now();

for(let i = 0; i < 10000; i++) {
console.log(i);
}

// Capture the end time
const endTime = performance.now();

// Calculate the elapsed time
const elapsed = endTime - startTime;

console.log('Elapsed time:', elapsed, 'milliseconds'); // Elapsed time: 211.9000000357628 milliseconds