setTimeout 停止 while 循环

发布于 2024-09-14 23:56:16 字数 399 浏览 8 评论 0原文

我使用 setTimeout 设置了幻灯片放映 (Slideshow()),效果很好。我需要将幻灯片放映限制为 3 次重复,但是当我添加 while 循环 (Count()) 时,它会打印 Test 1 并停止

function SlideShow()
{
  setTimeout("document.write('Test 1')", 1500);
  setTimeout("document.write('Test 2')", 3000);
  setTimeout("document.write('Test 3')", 4500);
}

function Count()
{
  var i=0;

  do
  {
    SlideShow();
    i++;
  }
  while (i<=3);
}

I set up a slide show (Slideshow()) using setTimeout, and it works fine. I need to limit the slide show to 3 repeats, but when I add a while loop (Count()) it it prints Test 1 and stalls

function SlideShow()
{
  setTimeout("document.write('Test 1')", 1500);
  setTimeout("document.write('Test 2')", 3000);
  setTimeout("document.write('Test 3')", 4500);
}

function Count()
{
  var i=0;

  do
  {
    SlideShow();
    i++;
  }
  while (i<=3);
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

拥抱影子 2024-09-21 23:56:16

这对我有用:

    function slideShow() {
        setTimeout("alert('1');", 1500); 
        setTimeout("alert('2');", 3000); 
        setTimeout("alert('3');", 4500); 
    }

    function count() {
        for(var i=0; i<3; i++) {
            slideShow();
        }
    }

    count();

This works for me:

    function slideShow() {
        setTimeout("alert('1');", 1500); 
        setTimeout("alert('2');", 3000); 
        setTimeout("alert('3');", 4500); 
    }

    function count() {
        for(var i=0; i<3; i++) {
            slideShow();
        }
    }

    count();
莫相离 2024-09-21 23:56:16

您可以只使用一次超时,如下所示:

<img id="theImg" />
<script>
    var cnt = 2,
        i = 0,
        pics = [
            'image1.png',
            'image2.png',
            'image3.png'
        ];
    function SlideShow(ap){
        if(ap[i]){
            //set the src of theImg to the item i of the array
            document.getElementById('theImg').src = ap[i++];
            setTimeout(function(){
                SlideShow(ap);
            }, 1500);
        }else if(cnt--){
            i = 0;
            SlideShow(pics);
        }
    }
    SlideShow(pics);
</script>

You could just use one timeOut like in:

<img id="theImg" />
<script>
    var cnt = 2,
        i = 0,
        pics = [
            'image1.png',
            'image2.png',
            'image3.png'
        ];
    function SlideShow(ap){
        if(ap[i]){
            //set the src of theImg to the item i of the array
            document.getElementById('theImg').src = ap[i++];
            setTimeout(function(){
                SlideShow(ap);
            }, 1500);
        }else if(cnt--){
            i = 0;
            SlideShow(pics);
        }
    }
    SlideShow(pics);
</script>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文