Scheduling / Timing
Advanced Functions: Scheduling: setTimeout / setInterval
What are the two most common JavaScript methods used for scheduling a call?
View Answer:
Interview 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 it continuously. Both methods are helpful when you need to schedule specific events or actions in JavaScript.
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.
Can you explain the function and syntax of the setTimeout() method?
View Answer:
Interview Response: The setTimeout method sets a timer that executes a function or piece of code once the timer expires. It takes several arguments and parameters, including the callback function, delay time, and optional parameters. The delay time is optional and get specified in milliseconds; however, it must be a positive integer. The callback's optional parameter gets utilized to set values.
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], ...);
Syntax: let timerId = setTimeout(func|code, [delay], [arg1], [arg2], ...);
function sayHi() {
alert('Hello');
}
setTimeout(sayHi, 1000);
// setTimeout without arguments:
function sayHi(phrase, who) {
alert(phrase + ', ' + who);
}
setTimeout(sayHi, 1000, 'Hello', 'John'); // Hello, John
// Arrow function implementation
setTimeout(() => alert('Hello'), 1000);
note
We can use the clearTimeout method to clear setTimeout in our code.
Can you explain the function and syntax of the clearTimeout() method?
View Answer:
Interview Response: The clearTimeout method clears a timer set with the setTimeout method. The timer value returned by setTimeout gets used as the clearTimeout method parameter.
Code Example:
let timerID = setTimeout(() => alert('never happens'), 1000);
alert(timerID); // timer identifier
clearTimeout(timerID);
alert(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 and syntax of the setInterval() method?
View Answer:
Interview Response: The setInterval method sets an interval that executes a function or piece of code repeatedly until the interval clears using the clearInterval method. It takes several arguments and parameters, including the callback function, interval time, and optional parameters. The interval delay time is optional and can be set in milliseconds to control the interval delay, but it must be a positive integer. The optional parameters gets used to set values in the callback function.
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], ...);
Syntax: let timerId = setInterval(func|code, [delay], [arg1], [arg2], ...);
// repeat with the interval of 2 seconds
let timerId = setInterval(() => alert('tick'), 2000);
// after 5 seconds stop
setTimeout(() => {
clearInterval(timerId);
alert('stop');
}, 5000);
How does garbage collection work with the setInterval and setTimeout callbacks?
View Answer:
Interview Response: When a function gets passed in setInterval or 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, but for setTimeout the variables are alive until the callback is complete.
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
setTimeout(function() {...}, 100);
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: In JavaScript, zero delay setTimeout schedules the function call execution after the current execution is complete. The function gets scheduled to run after the current script.
Code Example:
setTimeout(() => alert('World')); // returns second
alert('Hello'); // returns first
note
There are also advanced browser-related use cases of the zero-delay timeout, such as splitting CPU-hungry tasks.