幻灯片效果奇怪

Slideshow Works Strangely

我正在制作幻灯片以供学习,但效果很奇怪。 只有第一个和第二个 li 元素重复移动。我无法很好地解释这种现象。 这是我的代码。

timer();
function timer(){
 setInterval(function(){slide()}, 2000);
}
function slide(){
 $('.imgs').animate({left:'-300px'},1000,function(){
  $(this).css({'left':0});
  $(this).append($(this).children('.img').eq(0));
 });
}
ul {padding: 0; margin: 0;}
li {list-style: none;}

#box {width: 300px; height: 200px; margin: 50px auto; position: relative; overflow: hidden;}
.imgs {width: 900px; height: 200px; position: relative;}
.img {width: 300px; height: 200px; float: left; position: relative;}

.img:first-child {background: pink;}
.img:nth-child(2) {background: skyblue;}
.img:nth-child(3) {background: grey;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

<div id="box">
  <ul class="imgs">
    <li class="img"></li>
    <li class="img"></li>
    <li class="img"></li>
  </ul>
</div>

将元素移动-300px,直到达到 li 元素的总数

如果计数器达到 li 元素的总数则重置它

到达最后一个元素集后-0px

timer();
function timer(){
 setInterval(slide(), 2000);
}
function slide(){
    var imageWidth = 300
    var totalElm = $(".imgs .img").length 
    $('.imgs').width(totalElm*imageWidth)
    var counter = 0 
    return function(){
        var next = counter + 1 
        if(next < totalElm){
            var left = next * imageWidth
            $('.imgs').animate({left:'-'+left+'px'},1000,function(){
                counter++
            });
        }else{
            $('.imgs').animate({left:'-0px'},1000,function(){
                counter = 0
            });
        }
    }
}
ul {padding: 0; margin: 0;}
li {list-style: none;}

#box {width: 300px; height: 200px; margin: 50px auto; position: relative; overflow: hidden;}
.imgs {width: 900px; height: 200px; position: relative;}
.img {width: 300px; height: 200px; float: left; position: relative;}

.img:first-child {background: pink;}
.img:nth-child(2) {background: skyblue;}
.img:nth-child(3) {background: grey;}
.img:nth-child(4) {background: red;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="box">
    <ul class="imgs">
        <li class="img"></li>
        <li class="img"></li>
        <li class="img"></li>
        <li class="img"></li>
    </ul>
</div>