我想在 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)
然后顺序发生变化,因为 setTimeout
是 async 在这种情况下它会被触发 after 它的计时器到期(JS 继续并执行 function2()
同时)
如果您的上述代码有问题,那么您的任一函数都包含异步代码(setInterval()
、setTimeout()
、 DOM 事件、WebWorker 代码等),这让您感到困惑。
- async 这里代表异步 意思是不按特定顺序发生
关于javascript - 在 setTimeout 中调用超过 1 个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29839996/