【问题标题】:Javascript pause within function [duplicate]函数内的Javascript暂停[重复]
【发布时间】:2021-08-28 13:40:10
【问题描述】:

在下面的示例中,我想在更改元素一的样式后暂停脚本。然后在 500 毫秒后,继续更改元素 2 的样式。由于setTimeout()需要一个函数参数,如何在不延迟整个函数的情况下实现呢?

注意:该函数由onclick="myFunction()" 在 HTML 元素上调用。

function myFunction() {

    // Declare some variables
    var elementOne = document.getElementById("classElementOne");
    var elementTwo = document.getElementById("classElementTwo");

    // Execute for element 1
    elementOne.style.cssText = "some styles";

    // Wait 500 miliseconds

    // Execute for element 2
    elementTwo.style.cssText = "some styles";
}

【问题讨论】:

  • 为什么settimeout会延迟整个函数?
  • 不延迟整个函数”是什么意思?你能告诉我们你会如何使用setTimeout吗?

标签: javascript settimeout delay


【解决方案1】:

由于setTimeout()需要一个函数参数,我该如何实现呢 不耽误整个功能?

您可以使用setTimeout() 并传递一个更改元素 2 样式的函数。

它不会延迟您的整个功能。 (在你的例子中myFunction)。相反,它只是延迟了您作为参数传入的匿名函数的执行。

function myFunction() {

    // Declare some variables
    var elementOne = document.getElementById("classElementOne");
    var elementTwo = document.getElementById("classElementTwo");

    // Execute for element 1
    elementOne.style.cssText = "some styles";

    // Wait 500 miliseconds
    setTimeout(function(){ 
     // Execute for element 2
     elementTwo.style.cssText = "some styles"; 
     }, 500);
}

【讨论】:

    【解决方案2】:
    function myFunction() {
    
        // Declare some variables
        var elementOne = document.getElementById("classElementOne");
        var elementTwo = document.getElementById("classElementTwo");
    
       // Execute for element 1
       elementOne.style.cssText = "some styles";
    
       // Wait 500 miliseconds
    
       // Execute for element 2
       setTimteout(() => {
         elementTwo.style.cssText = "some styles";
       }, 500);  
    }
    

    【讨论】:

      【解决方案3】:

      我猜你只是把你想要延迟的代码放在一个匿名函数中,如下所示:

      function myFunction() {
      
          // Declare some variables
          var elementOne = document.getElementById("classElementOne");
          var elementTwo = document.getElementById("classElementTwo");
      
          // Execute for element 1
          elementOne.style.cssText = "some styles";
      
          // Wait 500 miliseconds
      
          // Execute for element 2
          setTimteout(() => {
              elementTwo.style.cssText = "some styles";
          }, 500);
      }
      

      【讨论】:

      • 样式更改应该在setTimeout,而不是变量声明中
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多