What Is the Third Argument in JavaScript setTimeout()?

The JavaScript setTimeout() method has the following syntax:

setTimeout(function[, delay, arg1, arg2, ...]);

Starting from the (optional) third argument, you can specify an arbitrary number of arguments to the JavaScript setTimeout() method, which are all passed through to the provided timeout callback function. For example:

function timeoutFunc(...args){
    console.log(args[0], args[1], args[2]);
}

setTimeout(timeoutFunc, 500, 'foo', 'bar', 'baz'); // 'foo bar baz'

You can have many possibilities with this. For example, you could use this with a Promise to resolve with a value provided in the third argument:

const promise = new Promise((resolve, reject) => {
  setTimeout(resolve, 1000, 'foo');
});

promise.then((val) => console.log(val)); // 'foo'

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.