We all use modern web browsers, and performance is among the most critical aspects of web browsing. Modern web browsers must execute complex programs as well as being reactive to users’ interactions.
setTimeout and setInterval are two methods in JavaScript used to run code or a function asynchronously, allowing us to run them at specific time intervals.
First and foremost, let’s look at these two methods and their functionalities. Then, this article will discuss their limitations in modern browsers.
setTimeout
We can use the setTimeout() method to run a function after a specified waiting time. setTimeout() accepts three parameters.
Syntax
setTimeout(function|code, delay, arg0,arg1,...)
- function | code: A function to be executed after a specified waiting time. We can include a string instead of a function, but it is not recommended, as it is an enormous security risk.
- delay: The time in milliseconds that should pass between each execution of the code or function. The default value is 0.
- arg1,arg2, .. : Additional arguments passed through to the function.
Here is an example of displaying the string “Example of a setTimeout(), which will run after a second.” after a delay of one second.
function exampleFunc() { alert('Example of a setTimeout(),which will run after a second.'); } setTimeout(exampleFunc, 1000);
The clearTimeout() function cancels the timer event. Also, it stops the function execution.
let timerID = setTimeout(exampleFunc, 1000); clearTimeout(timerID);
Syncfusion JavaScript UI controls are the developers’ choice to build user-friendly web applications. You deserve them too.
setTimeout with zero delay
Using setTimeout() with zero delay schedules function execution as soon as possible when the current other queued tasks are finished.
Syntax
setTimeout(function|code, 0) setTimeout(function|code)
setInterval
Use the setInterval() method to run a function repeatedly after a delay time. The only difference between setInterval and setTimeout() is that setInterval will call a function or execute a code repeatedly with a given delay time. Both setTimeout() and setInterval() allow the same three parameters.
Syntax
setInterval(function|code, delay, arg0,arg1,..)
Here is an example of displaying the string “Example of a setInterval(), which will run every second.” every second.
function exampleFunc2() { alert('Example of a setInterval(),which will run every second.'); } setInterval(exampleFunc2, 1000);
The clearInterval() function cancels the timer events. Also, it stops the function execution.
let timerID2 = setInterval(exampleFunc2, 1000); clearInterval(timerID2);
What is best for recursive calls?
The next call is scheduled to begin after the current one with the setTimeout(). Therefore setTimeout() is best used recursively instead of setInterval(), as it has more control over delays.
With setTimeout(), we can define our next call differently based on the current call results. For example, if we have a service that retrieves or checks data every 10 seconds, but the server is overloaded, we can increase the delay seconds. If the service or the function is CPU-intensive, we can analyze the execution time and decide whether to plan the next call sooner or later.
The setTimeout and setInterval can create macro tasks. A macro task is a small function executed after the JavaScript execution stack and microtasks have been cleared.
Every property of the Syncfusion JavaScript controls is completely documented to make it easy to get started.
Limitations in Modern Browsers
setTimeout and setInterval are not accurate
The browser runs all of the JavaScript on your website on a single thread. Therefore, setTimeout and setInterval will be added to the task queue. The JavaScript event loop continuously checks the task queue for events or tasks waiting to be executed. When the event loop detects that the task queue is not empty, it dequeues the first task in the queue and executes it.
At that moment, if the task’s scheduled time has not yet come to pass, the task will be maintained in the queue until its scheduled time is reached. If the scheduled time has already passed and the task is in the queue, the event loop dequeues the task and executes it immediately.
In such cases, functions take longer than the delay specified in the methods.
The following image shows how things work in a web browser at a high level.
According to HTML Living Standard, “This API does not guarantee that timers will run exactly on schedule. Delays due to CPU load, other tasks, etc., are to be expected.”
Delays in “setTimeout with zero delay”
Even though it says setTimeout with zero delays, the browser has limitations for nested timers.
According to HTML Living Standard, “Timers can be nested; after five such nested timers, however, the interval is forced to be at least four milliseconds.”
Although you haven’t given setTimeout a specific time limit, it must wait for all the code for queued messages to finish.
Exposure to security vulnerabilities
The setTimeout() and setInterval() functions can execute text specified through them, exposing them to DOM-based, cross-site scripting (XSS). Therefore, you shouldn’t pass any sensitive data via those functions.
Memory leaks
During execution, a JavaScript program is assigned three types of memory, the code area, the call stack, and the heap. Using setTimeout and setInterval can cause memory leaks, as they will have heavy object references kept in their callbacks or active in memory. On the other hand, uncleared timers can run indefinitely if we forget to clear the timer with clearInterval or clearTimeout.
To make it easy for developers to include Syncfusion JavaScript controls in their projects, we have shared some working ones.
Browser support
The following image from mozilla.org shows the browser compatibility for setInterval.
The following image from mozilla.org shows the browser compatibility for setTimeOut.
We should consider these limitations when using the setTimeout and setInterval. We can use alternatives and get relatively accurate set intervals and set timeouts by using a while statement or requestAnimationFrame. We should not pass a string instead of a function.
Conclusion
The setTimeout and setInterval methods are used to schedule tasks for a specific time. In this article, we discussed what these methods are and their limitations in modern browsers.
These limitations are not to be taken lightly. Choosing what to use when based on your requirements and considering the browser limitations would be best.
Thank you for reading!
Syncfusion’s Essential JS 2 is the only suite you will need to build an app. It contains over 80 high-performance, lightweight, modular, and responsive UI components in a single package. Download a free trial to evaluate these controls today.
If you have any questions or comments, you can contact us through our support forums, support portal, or feedback portal. We are always happy to assist you!