Skip to content
the poor coder

javascript settimeout loop

Poor Man
Published
Reading time
1 min read

Javascript SetTimeout Loop#

If you are a javascript developer, you might have come across a situation where you need to execute some code after a certain delay. Javascript's setTimeout() method comes in handy in such a situation. It allows you to execute a function after a certain delay, specified in milliseconds.

But what if you want to execute the same code continuously with some delay between each execution? In other words, you want to create a loop with a delay between each iteration. One way to achieve this is by using setInterval() method. But sometimes, using setInterval() may cause issues like overlapping or missed execution if the code inside the function takes more time to execute than the interval time.

A better approach is to use setTimeout() recursively to create a loop. Here's an example:

Text

function loopFunc() {
  // Your code here
  setTimeout(loopFunc, 1000); // 1000 milliseconds delay
}

// Call the loopFunc() to start the loop
loopFunc();

In this example, the loopFunc() function contains the code that you want to execute repeatedly with a delay of 1000 milliseconds between each iteration. The function calls itself recursively using setTimeout().

Another way to achieve the same is by using an immediately invoked function expression (IIFE) with setTimeout(). Here's an example:

Text

(function loopFunc() {
  // Your code here
  setTimeout(loopFunc, 1000); // 1000 milliseconds delay
})();

In this example, the loopFunc() function is an IIFE that contains the code that you want to execute repeatedly with a delay of 1000 milliseconds between each iteration. The function calls itself recursively using setTimeout().

Both approaches are valid, and you can choose any one of them based on your preference.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC