Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling more than 1 function in setTimeout

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);
like image 695
RAHUL DEEP Avatar asked Apr 24 '15 06:04

RAHUL DEEP


2 Answers

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.

  • async here stands for asynchronous meaning not occurring in a particular order
like image 118
nicholaswmin Avatar answered Sep 22 '22 16:09

nicholaswmin


I've used this syntax and it works fine:

$('#element').on('keypress change', function (e) {
   setTimeout(function () { function1(); function2(); }, 500, $(this));
});
like image 36
Carmine Checker Avatar answered Sep 26 '22 16:09

Carmine Checker