【问题标题】:Delay in setTimeoutsetTimeout 中的延迟
【发布时间】:2019-09-12 06:23:57
【问题描述】:

我希望元素一次单独缩放一个,延迟 3 秒。此外,当缩放一个元素时,其他元素应该是正常的。目前,所有元素都一次缩放并在 4 秒后恢复正常。我对元素使用了 setTimeout 方法,并在每个元素之间提供了 3 秒的延迟,但它似乎没有工作。为了保持进程持续进行,我也使用了 setInterval() 并且延迟有 4 秒。我没有不知道我哪里出错了。这里是代码 sn-p 以便更好地理解。任何帮助将不胜感激。

function scale(element){

$(element).toggleClass('found');
}

function autoscale(){
setTimeout(scale('.icons .image:first-child li:first-child'),1000);
setTimeout(scale('.icons .image:first-child li:nth-child(2)'),4000);
setTimeout(scale('.icons .image:first-child li:nth-child(3)'),7000);
setTimeout(scale('.icons .image:last-child li:first-child'),10000);
setTimeout(scale('.icons .image:last-child li:nth-child(2)'),13000);
setTimeout(scale('.icons .image:last-child li:nth-child(3)'),16000);
}
autoscale();
setInterval(autoscale,4000);
  .found{
      transform: scale(1.2);
      z-index: 4!important;
  }
  .icons li{
    cursor: pointer;
    transition: 0.2s ease-in;
    list-style-type:none;
  }
   .icons li {
     position: relative;
     line-height: 20px;
     z-index: 2;
     border-radius: 50%;
     padding: 10px;
     width: 80px;
     height: 80px;
     background: linear-gradient(45deg, #a1c4fd,#c2e9fb);
     display: inline-flex;
     align-items: center;
     justify-content: center;     
  }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

  <div class="icons">

       <div class="image">
           <ul>
              <li>
                 <p>A</p>
               </li>
               <li>
                  <p>B</p>
                </li>
                <li>
                   <p>C</p>
                 </li>  
            </ul>              
         </div>
         <div class="image">
             <ul>
                 <li>
                     <p>D</p>
                  </li>
                  <li>
                      <p>E</p>
                   </li>
                   <li>
                       <p>F</p>
                   </li>
              </ul>
          </div>
     </div>

【问题讨论】:

    标签: jquery settimeout setinterval


    【解决方案1】:

    setTimeout() 将函数作为其第一个参数。您正在调用函数scale() 并将其返回值提供给setTimeout()。因此,您的代码实际上与此相同:

    var ret = scale('.icons .image:first-child li:first-child');
    setTimeout(ret ,1000);
    

    所以你可以看到scale() 被立即调用。

    你需要给它一个函数,例如

    setTimeout(function() { scale('.icons .image:first-child li:first-child') }, 1000);
    

    这样在超时后调用函数,然后在内部调用scale()

    【讨论】:

    • 哦,我明白了。我认为我们必须将函数作为参数传递,所以我将 scale 函数作为参数传递给 setTimeout。非常感谢。
    猜你喜欢
    • 2010-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-08
    • 2012-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多