繁体   English   中英

在 setTimeout 中调用 1 个以上的函数

[英]Calling more than 1 function in setTimeout

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

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

是否可以?

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

哪个会先执行?

除非您使用基于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异步的,在这种情况下,它会计时器到期后被触发(JS 继续并同时执行function2()


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

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

我已经使用了这种语法,它工作正常:

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

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():

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM