Calling more than 1 function in setTimeout
Is it possible?
Yes, why not? setTimeout
takes a callback function as its first argument. The fact that this is a callback function doesn't change anything; normal rules apply.
which one will be executed first?
If you don't use Promise
-based or callback -based code, the Javascript runs sequentially, so your functions will be called in the order you wrote them.
setTimeout(function() {
function1() // runs first
function2() // runs second
}, 1000)
However, if you do this:
setTimeout(function() {
// after 1000ms, call the 'setTimeout' callback
// In the meantime, continue executing code below
setTimeout(function() {
function1() //runs second after 1100ms
},100)
function2() //runs first, after 1000ms
},1000)
then the order changes since it setTimeout
is asynchronous, in which case it is started after the timer expires (JS continued and in the meantime executed function2()
)
If you have the above code with the problem, any of your function contains an asynchronous code ( setInterval()
, setTimeout()
, the DOM event, WebWorker code, etc.) that confuses you.
- asynchronous here means an asynchronous value that does not appear in a specific order.
source to share