【问题标题】:Calling more than 1 function in setTimeout在 setTimeout 中调用超过 1 个函数
【发布时间】:2015-04-24 06:14:38
【问题描述】:
我想在 JavaScript 中一个 setTimeout() 的末尾调用两个函数。
是否有可能,如果“是”,将首先执行哪个?
setTimeout(function() {
playmp3(nextpage);
$.mobile.changePage($('#' + nextpage));
}, playTime);
【问题讨论】:
标签:
javascript
jquery
jquery-mobile
【解决方案1】:
有可能吗?
是的,为什么不呢? 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 的顺序发生变化,在这种情况下它会被触发 在它的计时器到期(JS 继续并在此期间执行 function2())
如果您对上述代码有疑问,那么您的任一函数都包含 async 代码(setInterval()、setTimeout()、DOM 事件、WebWorker 代码等),这会让您感到困惑。 p>
-
async 这里代表 asynchronous 意思是不按特定顺序发生
【解决方案2】:
我用过这个语法,效果很好:
$('#element').on('keypress change', function (e) {
setTimeout(function () { function1(); function2(); }, 500, $(this));
});
【解决方案3】:
5这对我来说就像一个魅力(点击一个元素后触发的多个函数):
const elem = document.getElementById("element-id");
function parent(){
elem.addEventListner("click", func1);
function func1(){
// code here
setTimeout(func2, 250) //func2 fires after 200 ms
}
function func2(){
// code here
setTimeout(func3, 100) //func3 fires 100 ms after func2 and 350 ms after func1
}
function func3(){
// code here
}
}
parent():