JavaScript动画setInterval / clearInterval

JavaScript animation setInterval / clearInterval

我需要制作动画: 一个变宽并向右移动直到达到尺寸限制然后再次变薄的盒子。 (我尝试给"bigger"区间赋予更高的值,然后清除它并让"smaller"区间继续播放并缩小它, 它实际上做了什么:它达到 200px 然后重复变大和变小 5px 并继续向右移动)

 function animatesmall(name, dist, time) {
     $(name).animate({
         left: dist
     }, time);
     $(name).css({
         width: numberup
     });
     numberup = numberup - 5;
 }

 var numberup = 1;

 function animatebig(name, dist, time) {
     if (numberup < 200) {
         $(name).animate({
             left: dist
         }, time);
         $(name).css({
             width: numberup
         });
         numberup = numberup + 10;
     } else {
         clearInterval(bigger);
     }
 }

 $(function () {
     var bigger = setInterval(function () {
         animatebig('.box1', "+=1", 100)
     }, 100);

     var smaller = setInterval(function () {
         animatesmall('.box1', "+=1", 100)
     }, 100);
 });

在 "numberup" 达到 200 之前,您实际上是在宽度中增加 10 并减去 5

超过200只减5

然后,因为 "bigger" 没有在 $(function() 范围之外定义,所以 animatebig 仍然被调用,这就是为什么框的大小会振荡

这样写代码似乎更有效率

$(function () {
    var numberup = 1;
    var delta = 5;

    function animate(name, dist, time) {
        if (delta > 0 && numberup >= 200) {
            delta = -5;
        }
        else if (numberup < 0) {
            clearInterval(timer);
        }
        $(name).animate({
            left: dist
        }, time);
        $(name).css({
            width: numberup
        });
        numberup += delta;
    }
    var timer = setInterval(function () {
        animate('.box1', "+=1", 100)
    }, 100);
});

这有一个间隔,增长 5,然后缩小 5 ...你可能想在 width < 0 时停止

为了更流畅的动画效果,我建议查看 requestAnimationFrame