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);

      

+4


source to share


2 answers


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.
+14


source


I have used this syntax and it works great:



$('#element').on('keypress change', function (e) {
   setTimeout(function () { function1(); function2(); }, 500, $(this));
});

      

0


source







All Articles