Scheduling / Timing
Advanced Functions: Scheduling: setTimeout / setInterval
What are the two most common JavaScript methods used for scheduling a call?
View Answer:
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:
Can you explain the function of the setTimeout() method?
View Answer:
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);
We can use the clearTimeout method to clear setTimeout in our code.
How do you cancel a scheduled setTimeout call?
View Answer:
// 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:
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)
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:
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:
// 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);
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:
setTimeout(() => console.log('JavaScript!')); // returns second
console.log('Hello'); // returns first
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:
// 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:
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:
// 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:
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:
What is the impact of using setInterval on browser performance?
View Answer:
How can you handle errors in setTimeout and setInterval callbacks?
View Answer:
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:
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:
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:
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:
// 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