Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to chain setTimeout functions in JavaScript?

Is it possible to chain setTimout functions to ensure they run after one another?

like image 369
xiatica Avatar asked Aug 03 '11 03:08

xiatica


People also ask

Does setTimeout work synchronously?

Working with asynchronous functionssetTimeout() is an asynchronous function, meaning that the timer function will not pause execution of other functions in the functions stack. In other words, you cannot use setTimeout() to create a "pause" before the next function in the function stack fires.

How do you wrap setTimeout in Promise?

setTimeout() is not exactly a perfect tool for the job, but it's easy enough to wrap it into a promise: const awaitTimeout = delay => new Promise(resolve => setTimeout(resolve, delay)); awaitTimeout(300). then(() => console. log('Hi')); // Logs 'Hi' after 300ms const f = async () => { await awaitTimeout(300); console.

What is the alternative for setTimeout in JavaScript?

The setInterval method has the same syntax as setTimeout : let timerId = setInterval(func|code, [delay], [arg1], [arg2], ...) All arguments have the same meaning. But unlike setTimeout it runs the function not only once, but regularly after the given interval of time.

Is setTimeout in a different thread?

No, it doesn't. "Execution context" doesn't mean "thread", and until recently Javascript had no support for anything resembling threads. What actually happens is that an event is pushed onto the event queue that's set to execute in the number of milliseconds specified by the second argument to SetTimeout/SetInterval.


3 Answers

Three separate approaches listed here:

  1. Manually nest setTimeout() callbacks.
  2. Use a chainable timer object.
  3. Wrap setTimeout() in a promise and chain promises.

Manually Nest setTimeout callbacks

Of course. When the first one fires, just set the next one.

setTimeout(function() {
    // do something
    setTimeout(function() {
        // do second thing
    }, 1000);
}, 1000);

Chainable Timer Object

You can also make yourself a little utility object that will let you literally chain things which would let you chain calls like this:

delay(fn1, 400).delay(fn2, 500).delay(fn3, 800);

function delay(fn, t) {
    // private instance variables
    var queue = [], self, timer;
    
    function schedule(fn, t) {
        timer = setTimeout(function() {
            timer = null;
            fn();
            if (queue.length) {
                var item = queue.shift();
                schedule(item.fn, item.t);
            }
        }, t);            
    }
    self = {
        delay: function(fn, t) {
            // if already queuing things or running a timer, 
            //   then just add to the queue
        	  if (queue.length || timer) {
                queue.push({fn: fn, t: t});
            } else {
                // no queue or timer yet, so schedule the timer
                schedule(fn, t);
            }
            return self;
        },
        cancel: function() {
            clearTimeout(timer);
            queue = [];
            return self;
        }
    };
    return self.delay(fn, t);
}

function log(args) {
    var str = "";
    for (var i = 0; i < arguments.length; i++) {
        if (typeof arguments[i] === "object") {
            str += JSON.stringify(arguments[i]);
        } else {
            str += arguments[i];
        }
    }
    var div = document.createElement("div");
    div.innerHTML = str;
    var target = log.id ? document.getElementById(log.id) : document.body;
    target.appendChild(div);
}


function log1() {
	  log("Message 1");
}
function log2() {
	  log("Message 2");
}
function log3() {
	  log("Message 3");
}

var d = delay(log1, 500)
    .delay(log2, 700)
    .delay(log3, 600)

Wrap setTimeout in a Promise and Chain Promises

Or, since it's now the age of promises in ES6+, here's similar code using promises where we let the promise infrastructure do the queuing and sequencing for us. You can end up with a usage like this:

Promise.delay(fn1, 500).delay(fn2, 700).delay(fn3, 600);

Here's the code behind that:

// utility function for returning a promise that resolves after a delay
function delay(t) {
    return new Promise(function (resolve) {
        setTimeout(resolve, t);
    });
}

Promise.delay = function (fn, t) {
    // fn is an optional argument
    if (!t) {
        t = fn;
        fn = function () {};
    }
    return delay(t).then(fn);
}

Promise.prototype.delay = function (fn, t) {
    // return chained promise
    return this.then(function () {
        return Promise.delay(fn, t);
    });

}

function log(args) {
    var str = "";
    for (var i = 0; i < arguments.length; i++) {
        if (typeof arguments[i] === "object") {
            str += JSON.stringify(arguments[i]);
        } else {
            str += arguments[i];
        }
    }
    var div = document.createElement("div");
    div.innerHTML = str;
    var target = log.id ? document.getElementById(log.id) : document.body;
    target.appendChild(div);
}

function log1() {
    log("Message 1");
}

function log2() {
    log("Message 2");
}

function log3() {
    log("Message 3");
}

Promise.delay(log1, 500).delay(log2, 700).delay(log3, 600);

The functions you supply to this version can either by synchonrous or asynchronous (returning a promise).

like image 181
jfriend00 Avatar answered Nov 14 '22 23:11

jfriend00


Inspired by @jfriend00 I demonstrated a shorter version:

Promise.resolve()
  .then(() => delay(400))
  .then(() => log1())
  .then(() => delay(500))
  .then(() => log2())
  .then(() => delay(800))
  .then(() => log3());

function delay(duration) {
  return new Promise((resolve) => {
    setTimeout(resolve, duration);
  });
}

function log1() {
  console.log("Message 1");
}

function log2() {
  console.log("Message 2");
}

function log3() {
  console.log("Message 3");
}
like image 21
Penny Liu Avatar answered Nov 14 '22 23:11

Penny Liu


If your using Typescript targeting ES6 this is pretty simple with Async Await. This is also very very easy to read and a little upgrade to the promises answer.

//WARNING: this is Typescript source code
//expect to be async
async function timePush(...arr){
    function delay(t){
        return new Promise((resolve,reject)=>{
            setTimeout(()=>{
                resolve();
            },t)
        })
    }
    //for the length of this array run a delay
    //then log, you could always use a callback here
    for(let i of arr){
        //pass the items delay to delay function
        await delay(i.time);
        console.log(i.text)
    }
}


timePush(
    {time:1000,text:'hey'},
    {time:5000,text:'you'},
    {time:1000,text:'guys'}
);
like image 34
Adam Miles Crockett Avatar answered Nov 14 '22 21:11

Adam Miles Crockett