简体   繁体   中英

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?

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);
}

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

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

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);

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
     */
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM