简体   繁体   中英

executing a series of function calls after setTimeout - JavaScript

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 ?

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.

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