user3324865
user3324865

Reputation: 163

JavaScript delay between functions using setTimeout(function, delay)

I want my program to be executed with delay between each execution. Now I have this:

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

There is delay between each execution of function0 but not between function1 and funtion2, function2 is run immediately after function1. How do I solve this?

Upvotes: 0

Views: 211

Answers (4)

Charlie
Charlie

Reputation: 11777

setTimeout is non blocking, so all three of those functions will run after 3 seconds. Changing it to something like this:

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

Will cause them each to run 3 seconds apart. If you didn't want to hardcode this, you could use setInterval, increment the function name (since your functions have numbers to distinguish between them), then stop after x amount of iterations:

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

Upvotes: 0

David Knipe
David Knipe

Reputation: 3454

Or you could do this:

function function0() {
    setTimeout(function1, 3000);
}
function function1() {
    /*
     Your code here
     */
    setTimeout(function2, 3000);
}
function function2() {
    /*
     Your code here
     */
    setTimeout(function3, 3000);
}
function function3() {
    /*
     Your code here
     */
}

Upvotes: 0

Allan Stepps
Allan Stepps

Reputation: 1067

This is not elegant, but it should work.. At the end of function 2, function 1 will be execute around 3 seconds later, same between function 1 and loop function.

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

        setTimeout(function() {
            // <my_function1>

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

Upvotes: 2

Jonathan
Jonathan

Reputation: 9151

All functions are executed after 3 seconds. Did you mean to do this:

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

Upvotes: 0

Related Questions