在setTimeout中调用多个函数 [英] Calling more than 1 function in setTimeout

查看:897
本文介绍了在setTimeout中调用多个函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在JavaScript中的一个setTimeout()的末尾调用两个函数. 是否可以,如果是",将首先执行哪个?

setTimeout(function() {
    playmp3(nextpage);
    $.mobile.changePage($('#' + nextpage));
}, playTime);

解决方案

有可能吗?

是的,为什么不呢? setTimeout使用回调 function 作为它的第一个参数.它是一个回调函数,这一事实不会改变任何东西.遵循通常的规则.

哪个首先执行?

除非您使用的是基于Promise或基于回调的代码,否则Javascript会顺序运行 ,因此将按照编写它们的顺序调用函数.

setTimeout(function() {
  function1() // runs first
  function2() // runs second
}, 1000)

但是,如果您这样做:

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)

然后顺序更改,因为setTimeout async ,在这种情况下,它会在计时器到期后被触发./p>


如果您的上述代码有问题,那么您的任何一个函数都将包含 async 代码(setInterval()setTimeout(),DOM事件,WebWorker代码等),这会使您感到困惑.

  • async 在这里代表 asynchronous ,这意味着它不是按特定顺序发生的

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.

  • async here stands for asynchronous meaning not occurring in a particular order

这篇关于在setTimeout中调用多个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆