简体   繁体   English

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

[英]Calling more than 1 function in setTimeout

I want to call two functions at the end of one setTimeout() in JavaScript.我想在 JavaScript 中的一个setTimeout()的末尾调用两个函数。 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. setTimeout需要一个回调函数,因为它是第一个参数。 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.除非您使用基于Promise或基于回调的代码,否则 Javascript 会按顺序运行,因此您的函数将按照您写下的顺序调用。

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)然后顺序发生变化,因为setTimeout异步的,在这种情况下,它会计时器到期后被触发(JS 继续并同时执行function2()


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

  • async here stands for asynchronous meaning not occurring in a particular order这里的async代表异步,意思是不按特定顺序发生

I've used this syntax and it works fine:我已经使用了这种语法,它工作正常:

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

5This worked like a charm for me (it's multiple functions that fire after an element is clicked): 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