I want to call two functions at the end of one setTimeout()
in JavaScript.
Is it possible and if "yes" which one will be executed first?
setTimeout(function() {
playmp3(nextpage);
$.mobile.changePage($('#' + nextpage));
}, playTime);
Is it possible?
Yes, why wouldn't it be? setTimeout
takes a callback function as it's 1st argument. The fact that it's a callback function doesn't change anything; the usual rules apply.
which one will be executed first?
Unless you're using Promise
-based or callback-based code, Javascript runs sequentially so your functions would be called in the order you write them down.
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 setTimeout
is async in which case it get's fired after it's timer expires (JS continued and executed function2()
in the meantime)
If you have issues with your above code then either one of your functions contains async code (setInterval()
,setTimeout()
, DOM event, WebWorker code etc), which confuses you.
I've used this syntax and it works fine:
$('#element').on('keypress change', function (e) {
setTimeout(function () { function1(); function2(); }, 500, $(this));
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With