0

I have the following piece of code:

    var gradient = new Gradient( element, [0, 0.99] );
    setTimeout( function(){
        gradient.push( [0, 0.99] );
    }, 3000);

    setTimeout( function(){
        gradient.pop();
    }, 3000);

    setTimeout( function(){
        gradient.shift();
    }, 3000);

    setTimeout( function(){
        gradient.map( function( stop ){
                return Math.min( 1, stop + 0.392 );
            });
    }, 3000);

    setTimeout( function(){
        gradient.unshift( 0 );
        gradient.pop();
    }, 3000);

    gradient.clear();

I have a radial gradient that changes after each function call ( a different operation on the gradient ). To finally demonstrate the change made by each function call, I set up a series of setTimeout() so the user can see the changes taking place. I was expecting after each function call, the corresponding operation to be performed, but when I test on the browser, only the last of the calls ( gradient.clear() ) is performed. I'm not sure the previous setTimeout calls are being executed, or it's being skipped until the last call. Any idea ?

1 Answer 1

5

You mustn't confuse setTimeout with pause. The MDN documentation defines setTimeout as

Calls a function or executes a code snippet after specified delay.

There is no mention of pausing the execution of the program.

setTimeout(f, 3000);
setTimeout(g, 3000);

h();

This code first executes the function h, then f and g three seconds after that (not simultaneously, weather g or f comes first may differ between implementations.)

What you are looking for is chaining of events - calling setTimeout from inside a setTimeout function.

What you want can be realized with an effect queue

var q = []

function run() {
    var item = q.shift();
    item.func();
    if (q.length > 0) {
        setTimeout(run, item.pause);
    }
}

q.push({ func: f1, pause: 1000 });
q.push({ func: f2, pause: 1000 });

run()​;

Here function f1 will execute, f2 will execute a second after that.

Sign up to request clarification or add additional context in comments.

1 Comment

Could you please give me more details?

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.