javascript - 在 setTimeout 中调用超过 1 个函数

标签 javascript jquery jquery-mobile

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

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

最佳答案

Is it possible?

是的,为什么不呢? setTimeout 将回调函数 作为第一个参数。它是一个回调函数这一事实并没有改变任何东西;通常的规则适用。

which one will be executed first?

除非您使用的是基于 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)

然后顺序发生变化,因为 setTimeoutasync 在这种情况下它会被触发 after 它的计时器到期(JS 继续并执行 function2() 同时)


如果您的上述代码有问题,那么您的任一函数都包含异步代码(setInterval()setTimeout()、 DOM 事件、WebWorker 代码等),这让您感到困惑。

  • async 这里代表异步 意思是不按特定顺序发生

关于javascript - 在 setTimeout 中调用超过 1 个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29839996/

相关文章:

javascript - 在真假之间切换

javascript - 如何查看用户输入的输入值 - 在控制台日志中单击

javascript - 从数组创建 li data-role=list-divider

html - 在移动平台上使图像适合 100% 宽度

jquery - 如何使用Phonegap和JqueryMobile上传文件?

javascript - 使用路由在angularJS中添加左右动画?

javascript - 分配 "/"热键以在搜索框上创建焦点用户

javascript - 样式化默认工具提示

Javascript函数编写约定

jquery - 如何使 HTML/CSS 百分比图表的边框变细?