jQuery setTimeout等待

时间:2017-11-24 10:48:35

标签: javascript jquery

我有一个简单的JS函数,可以为此表单进度设置动画条:

https://codepen.io/himanshu/pen/syLAh

这就是我现在的功能:

function makeAnimate() {

    var i = 1;
    $('.progress .circle').removeClass().addClass('circle');
    $('.progress .bar').removeClass().addClass('bar');
    setInterval(function() {

      $('.progress .circle:nth-of-type(' + i + ')').addClass('active');

      $('.progress .circle:nth-of-type(' + (i-1) + ')').removeClass('active').addClass('done');

      $('.progress .circle:nth-of-type(' + (i-1) + ') .label').html('✓');

      $('.progress .bar:nth-of-type(' + (i-1) + ')').addClass('active');

      $('.progress .bar:nth-of-type(' + (i-2) + ')').removeClass('active').addClass('done');

      i++;

      if (i==0) {
        $('.progress .bar').removeClass().addClass('bar');
        $('.progress div.circle').removeClass().addClass('circle');
        i = 1;
      }

    //Here i would do if i equal 3 wait in the loop extra 100ms
      if (i == 1) {

          setTimeout(function(){

            }, 100);      
      }  
      //Here i would do if i equal 3 wait in the loop extra 200ms
      if (i == 3) {  

          setTimeout(function(){    

            }, 200);      
      }
    }, 800);
}

它不起作用。我怎么能这样做等待exrta millisecs?

谢谢!

1 个答案:

答案 0 :(得分:0)

您需要的是提取动画功能并将其传递给间隔,将间隔保存为范围变量,以便您可以清除它并使用不同的超时分配新值。

这是一个有效的概念证明:

$(function() {
  var i = 0;
  var timeout = 1000; // 1 Second

  $('.timeout').text(timeout);
  $('.i').text(i);

  var animate = function() {
    if (i === 2) {
      timeout = 6000; // 6 Seconds

      clearInterval(interval);
      interval = setInterval(animate, timeout);
    }

    if (i === 3) {
      timeout = 1000; // Back to 1 second

      clearInterval(interval);
      interval = setInterval(animate, timeout);
    }
    
    if (i >= 7) {
      // Remember to clear the interval once your steps complete, otherwise it will run forever
      clearInterval(interval);
    }

    i++;

    $('.timeout').text(timeout);
    $('.i').text(i);
  }

  var interval = setInterval(animate, timeout);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Timeout: <span class="timeout"></span>
<br /> I: <span class="i"></span>