0

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?

2
  • What in the world are you trying to do? That code just runs each function 3 seconds later... Commented Mar 1, 2014 at 22:41
  • setTimeout is non-blocking. Commented Mar 1, 2014 at 22:48

4 Answers 4

2

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);
}
Sign up to request clarification or add additional context in comments.

Comments

0

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

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

Comments

0

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.