Using setTimeout() in JavaScript to create a delay between functions

Is there a way to add a delay between the execution of each function in my program? Currently, I have the following setup:

function function0() {
    setTimeout(function1, 3000);
    setTimeout(function2, 3000);
    setTimeout(function0, 3000);
}

While there is a delay between each execution of function0, there seems to be no delay between function1 and function2. How can I address this issue?

Answer №1

This solution may not be the most graceful, but it should get the job done. In this process, function 1 will be triggered around 3 seconds after function 2 finishes execution, and the same delay applies between function 1 and the loop function.

function function0() {
    setTimeout(function() {
        // <my_function2>

        setTimeout(function() {
            // <my_function1>

            setTimeout(function0, 3000);
        }, 3000);
    }, 3000);
}

Answer №2

Every action is carried out with a 3-second delay. Is this intentional?

function delayedFunctions() {
    setTimeout(firstFunction, 3000);
    setTimeout(secondFunction, 6000);
    setTimeout(delayedFunctions, 9000);
}

Answer №3

Alternatively, you have the option to execute the following code:

function doFunction0() {
    setTimeout(doFunction1, 3000);
}
function doFunction1() {
    /*
     Insert your code here
     */
    setTimeout(doFunction2, 3000);
}
function doFunction2() {
    /*
     Insert your code here
     */
    setTimeout(doFunction3, 3000);
}
function doFunction3() {
    /*
     Insert your code here
     */
}

Answer №4

setTimeout is designed to be non-blocking, allowing all three functions to execute after a 3-second delay. To stagger their execution at intervals of 3 seconds, you can modify the code like this:

function function0() {
    setTimeout(function1, 3000);
    setTimeout(function2, 6000);
    setTimeout(function0, 9000);
}

If you prefer not to hardcode the time intervals, you could utilize setInterval, incrementally change the function name (if they are numbered), and halt after a certain number of iterations:

var i = 0,
int = setInterval(function () {
    // Function logic
    i++;
    if (i === 3) {
        clearInterval(int);
    }
}, 1000);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble retrieving information from the JSON data received from the Google Place Search API

I'm encountering an issue with accessing data from the Google Place Search API. I've provided my code below for reference. getData = (keyword, location, country) => { let dataURI = `${URI}${keyword}+${location}+${country}${API}`; var ...

Optimal approach for reutilizing Javascript functions

After creating a simple quiz question using jQuery, involving show/hide, addClass, and tracking attempts, I am now considering how to replicate the same code for multiple questions. Would it be best practice to modify all variables in both HTML and jQuery, ...

Sharing context sub files in Next.js can be easily accomplished by following a few simple

These are the pages on my website: /pages /gift /[slug] index.tsx /personalize index.tsx In /gift/[slug]/index.tsx, I have a component called GiftProvider that looks like this: return ( <GiftProvider gift={gift}& ...

What is the best way to create a repetitive pattern using a for loop in Javascript?

I want to create a repeating pattern to color the background, but once i exceeds colors.length, the background color stops changing because, for example, colors[3] does not exist. I need colors[i] to start back at 0 until the first loop is complete. cons ...

Alter the color scheme of the website depending on the information provided by the user on the previous page

On the previous page, I have created a form with a checklist containing options for colors: red, green, and blue. If the user selects red, the background color on the next page should change to red. If green is selected, the background color will be green ...

Efficiently handling multiple responses in Express.js per single request

Currently exploring Node.js and working on a bot utilizing Dialogflow. I am aiming to establish a straightforward process: Step 1: Dialogflow sends a POST request with parameter param1 Step 2: My application replies with a waiting message (e.g., "your re ...

Adding an array of objects to a specific key using JavaScript

I'm facing a challenge with adding an array of objects to an existing array of objects using Vue.js. What I'm attempting to accomplish is creating a form repeater within another form repeater. While I was able to successfully implement the first ...

Formik causing malfunction in MUI DatePicker functionality

In my React project, I am using Formik to manage form processing and MUI UI components for the user interface. While I can select the day and month, I'm experiencing an issue with the year part not updating. Even when I manually type in a year in the ...

Encountering this error for the first time - Uncaught Error displayed in the Console

I have been working on a ToDo list and it is almost complete. However, I have encountered an unfamiliar error in the console that is preventing me from creating the list. The error message reads as follows: OPTIONS http://localhost:4000/cpds/add net::E ...

Having an issue with utilizing the useState hook in ReactJS for implementing pagination functionality

I'm struggling to resolve an issue with the React useState. What I'm trying to achieve is making an API call to fetch movies with pagination, but for some reason one of my states is showing up as undefined and it's puzzling me. The component ...

What is the proper way to utilize a variable within the translate3d function?

Currently, I am developing my portfolio and working on a function in JavaScript called translate3d(0,10px,0). My question is, how can I use a variable instead of hardcoding the value 10px? I attempted to use translate3d(0,a,0) where 'a' is a vari ...

A step-by-step guide on how to use the Google Closure Compiler: a

Is there anyone who could assist me in adding a snippet to the basic process of Google Closure Compiler? I have been trying unsuccessfully to do this via JavaScript code. I am using an example snippet from the official npm page, but when I run it, someth ...

Unexplainable space or padding issue detected in OwlCarousel grid gallery

There seems to be an unusual gap or margin at the bottom of each row section in this portfolio grid gallery that's running in OwlCarousel. You can view an example here. https://i.stack.imgur.com/NHOBd.png I've spent a lot of time trying to solv ...

Can someone explain why Array.from(classList)[0] is not changing to 'className'?

HTML Design <div class="custom-container color-red"> <h3>Hello, I am a customized container</h3> </div> Javascript Logic let element = document.getElementsByClassName('custom-container')[0]; let clas ...

What steps can I take to replicate a 'heap limit Allocation failed' error?

Context I encountered a challenging issue where my program displayed a FATAL ERROR: Reached heap limit Allocation failed - JavaScript heap out of memory This occurred when the memory usage reached around 512 mb Scavenge (reduce) 507.8 (518.9) -> 507.2 ...

Is Apache required for running NodeJs?

Recently, I set up a web project on my local machine following a tutorial. With the help of XAMPP, I was able to install MySQL and Apache to run my Node.JS backend. Now, I'm looking into hosting the project on an external server to make it accessible ...

Res.end isn't halting the script's execution process

I'm currently facing an issue while building an API around a third-party API in my Express route. The problem is that the script keeps executing even after encountering a 406 error. Below is the snippet of my code: app.get('/submit/:imei', a ...

JavaScript function for automatic scrolling to the bottom of the page is not functioning as expected

I'm working on incorporating a terminal/console feature into my website. I came across the JavaScript functions for scrolling down a page, namely window.scrollTo(0,document.body.scrollHeight); and window.scrollTo(0,document.querySelector(".fakeSc ...

What is the best way to programmatically select a checkbox that was created dynamically using jQuery?

I've been scouring the internet trying to find information on what I'm attempting to accomplish, but so far I haven't come across anything helpful. The issue I'm facing is with a form that has a section dynamically added using JavaScri ...

I'm encountering an undefined JavaScript variable, how should I proceed?

$(function(){ //Location was "set". Perform actions. $("#geocodesubmit").click(function(){ var geocoder = new google.maps.Geocoder(); geocoder.geocode( { 'address': address}, function(results, status) { if (status ...