【问题标题】:How do I restart a settimeout loop javascript after being cleared?清除后如何重新启动settimeout循环javascript?
【发布时间】:2012-10-22 09:25:34
【问题描述】:


我为纯 javascript-css tuorial 编写的一些代码一直存在问题。我是 javascript 的新手,我编写了这段代码来练习,但我认为这对于我为客户做的一些工作来说是完美的。要更改幻灯片,我有五个函数,第一个是启动 onload,然后我使用 settimeout 执行下一个,下一个,下一个,直到 5,当它循环回到一个,并进入无限循环,直到用户按下暂停(cleartimeout)。我的问题是,如何在停留在当前幻灯片(函数)上时重新启动 settimeout 循环?注意:我现在真的很想坚持使用 javascript,所以我宁愿没有 jquery 解决方案。

如果您想观看幻灯片演示:http://fudgepants.com/beta/slideshow/ 你可以按F12查看源代码。

【问题讨论】:

    标签: javascript slideshow settimeout


    【解决方案1】:

    您可以创建一个单独的函数来控制要调用的函数。我们称之为 showNextSlide()。

    此函数将有一个从 1 到 5 循环的绑定变量。它会在自身上调用 setTimeout() 并且要恢复,您只需再次调用该函数,因为它仍然知道它停止的位置。

    // keep a reference to the most recent setTimeout() call
    var timeOutId;
    
    function showNextSlide()
    {
        // initialize the bound variable for the first time
        // this variable gets preserved upon subsequent calls
        this.idx = this.idx || 0;
    
        switch (this.idx) {
            case 0:
                // code to show slide 1
                break;
            case 1:
                // show slide 2
                break;
            // etc.
        }
    
        // increase the counter and make sure it doesn't go over 4
        // i.e. 0, 1, 2, 3, 4, 0, 1, 2, 3, 4
        this.idx = (this.idx + 1) % 5;
    
        // call me in 5 seconds
        timeOutId = setTimeout(showNextSlide, 5000);
    }
    

    【讨论】:

    • 我明白你在说什么,但我不知道该怎么做。
    • @user1338292 抱歉,这似乎是一个愚蠢的问题,但什么是绑定变量,而且我不明白代码。我得到了开关部分,但不知道变量如何循环。我应该像写一个 1-5 的数组还是什么的。我只是不明白。很抱歉完全不理解。
    • @user1338292 所以百分号和数字就像说 while(this.idx
    • 有点。如果 (idx + 1 == 5) idx = 0;否则 idx++;
    • @user1338292 非常感谢!
    猜你喜欢
    • 2020-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多