Calling more than 1 function in setTimeout

风流意气都作罢 提交于 2020-06-25 03:25:51

问题


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

回答1:


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



回答2:


I've used this syntax and it works fine:

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


来源:https://stackoverflow.com/questions/29839996/calling-more-than-1-function-in-settimeout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!