setTimeout and setInterval Uses and Limitations in Modern Browsers
Live Chat Icon For mobile
Live Chat Icon
Popular Categories.NET  (174).NET Core  (29).NET MAUI  (207)Angular  (109)ASP.NET  (51)ASP.NET Core  (82)ASP.NET MVC  (89)Azure  (41)Black Friday Deal  (1)Blazor  (215)BoldSign  (14)DocIO  (24)Essential JS 2  (107)Essential Studio  (200)File Formats  (66)Flutter  (133)JavaScript  (221)Microsoft  (119)PDF  (81)Python  (1)React  (100)Streamlit  (1)Succinctly series  (131)Syncfusion  (915)TypeScript  (33)Uno Platform  (3)UWP  (4)Vue  (45)Webinar  (51)Windows Forms  (61)WinUI  (68)WPF  (159)Xamarin  (161)XlsIO  (36)Other CategoriesBarcode  (5)BI  (29)Bold BI  (8)Bold Reports  (2)Build conference  (8)Business intelligence  (55)Button  (4)C#  (147)Chart  (131)Cloud  (15)Company  (443)Dashboard  (8)Data Science  (3)Data Validation  (8)DataGrid  (63)Development  (628)Doc  (8)DockingManager  (1)eBook  (99)Enterprise  (22)Entity Framework  (5)Essential Tools  (14)Excel  (40)Extensions  (22)File Manager  (7)Gantt  (18)Gauge  (12)Git  (5)Grid  (31)HTML  (13)Installer  (2)Knockout  (2)Language  (1)LINQPad  (1)Linux  (2)M-Commerce  (1)Metro Studio  (11)Mobile  (507)Mobile MVC  (9)OLAP server  (1)Open source  (1)Orubase  (12)Partners  (21)PDF viewer  (43)Performance  (12)PHP  (2)PivotGrid  (4)Predictive Analytics  (6)Report Server  (3)Reporting  (10)Reporting / Back Office  (11)Rich Text Editor  (12)Road Map  (12)Scheduler  (52)Security  (3)SfDataGrid  (9)Silverlight  (21)Sneak Peek  (31)Solution Services  (4)Spreadsheet  (11)SQL  (10)Stock Chart  (1)Surface  (4)Tablets  (5)Theme  (12)Tips and Tricks  (112)UI  (387)Uncategorized  (68)Unix  (2)User interface  (68)Visual State Manager  (2)Visual Studio  (31)Visual Studio Code  (19)Web  (592)What's new  (332)Windows 8  (19)Windows App  (2)Windows Phone  (15)Windows Phone 7  (9)WinRT  (26)
setTimeout and setInterval Uses and Limitations in Modern Browsers

setTimeout and setInterval Uses and Limitations in Modern Browsers

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.

Web browser working structureAccording 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.

Web browsers compatibility for setIntervalThe following image from mozilla.org shows the browser compatibility for setTimeOut.

Web browsers compatibility for setTimeOutWe 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!

Related blogs

Tags:

Share this post:

Popular Now

Be the first to get updates

Subscribe RSS feed

Be the first to get updates

Subscribe RSS feed