setTimeout and setInterval Uses and Limitations in Modern Browsers
Tags: javascript, webdev
Published: 2023-03-24 05:43:26

---
title: setTimeout and setInterval Uses and Limitations in Modern Browsers
published: true
date: 2023-03-23 11:00:00 UTC
tags: javascript, webdev
canonical_url: https://www.syncfusion.com/blogs/post/settimeout-setinterval-uses-limitations.aspx
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/39b3ykesr8x6vimyn5yi.png
---
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**

```js
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.

```js
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.

```js
let timerID = setTimeout(exampleFunc, 1000);
clearTimeout(timerID);
```
### 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**

```js
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**

```js
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.

```js
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.

```js
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.

## 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 structure](https://www.syncfusion.com/blogs/wp-content/uploads/2023/03/Web-browser-working-structure-1-scaled.jpg)According to [HTML Living Standard](https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#timers "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](https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#timers "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**.

### Browser support

The following image from mozilla.org shows the browser compatibility for [setInterval.](https://developer.mozilla.org/en-US/docs/Web/API/setInterval "Getting started with setInterval()")

![Web browsers compatibility for setInterval](https://www.syncfusion.com/blogs/wp-content/uploads/2023/03/Web-browsers-compatibility-for-setInterval.png)The following image from mozilla.org shows the browser compatibility for [setTimeOut](https://developer.mozilla.org/en-US/docs/Web/API/setTimeout#browser_compatibility "Getting started with setTimeout()").

![Web browsers compatibility for setTimeOut](https://www.syncfusion.com/blogs/wp-content/uploads/2023/03/Web-browsers-compatibility-for-setTimeOut.png)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](https://www.syncfusion.com/javascript-ui-controls "Syncfusion JavaScript UI controls") 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](https://www.syncfusion.com/downloads/essential-js2 "Free evaluation of the Essential Studio products") to evaluate these controls today.

If you have any questions or comments, you can contact us through our [support forums](https://www.syncfusion.com/forums "Syncfusion Support Forum"), [support portal](https://support.syncfusion.com/ "Syncfusion Support Portal"), or [feedback portal](https://www.syncfusion.com/feedback/ "Syncfusion Feedback Portal"). We are always happy to assist you!

## Related blogs

- [JavaScript API Mocking Techniques](https://www.syncfusion.com/blogs/post/javascript-api-mocking-techniques.aspx "Blog: JavaScript API Mocking Techniques")
- [Top 8 JavaScript Notification Libraries](https://www.syncfusion.com/blogs/post/top-8-javascript-notification-libraries.aspx "Blog: Top 8 JavaScript Notification Libraries")
- [JavaScript String Manipulation Techniques Every Developer Should Know](https://www.syncfusion.com/blogs/post/javascript-string-manipulation-techniques-every-developer-should-know.aspx "Blog: JavaScript String Manipulation Techniques Every Developer Should Know")
- [Integrating JavaScript Scheduler with PHP and MySQL for Dynamic CRUD Operations](https://www.syncfusion.com/blogs/post/javascript-scheduler-with-php-and-mysql-for-dynamic-crud-operations.aspx "Blog: Integrating JavaScript Scheduler with PHP and MySQL for Dynamic CRUD Operations")