即使先清除,setTimeout 功能也会加倍

setTimeout functions double even when cleared first

我在 img/ 目录 (1-13.jpg) 中有图像,我需要遍历它们。 #next_container 应该 stop(); 循环,如果它已经 start();ed 并将 src 更改为 next(); 图像,然后再次 start();,但是当我点击 #next_container 时,它会按预期运行 next(); 函数,但由于某种原因 stop(); 不会停止旧的超时,我最终得到 two start(); 函数 运行 导致图像变化更快,当它被 stop();ed 时,#next_container 应该只得到 next(); 图像,但是对于循环 start();s 的某种原因。 #prev_container.

也是如此

HTML代码:

<div class="container">
    <img id="imgs" src="img/1.jpg" onload="start();">
    <div id="next_container" style="display: none;">
        <span id="next">&#x2771;</span>
    </div>
    <img id="player" src="" style="display: none;">
    <div id="prev_container" style="display: none;">
        <span id="prev">&#x2770;</span>
    </div>
    <p id="count">1 / 13</p>
</div>

JavaScript代码:

// the images array holds sources for all the images
function next(){
    var element = document.getElementById("imgs");
    var num = Number(element.src.split("/").slice(-1)[0].split(".")[0]);
    if (num == images.length){
        element.src = "img/1.jpg";
        document.getElementById("count").innerHTML = "1 / 13";
    } else {
        num++;
        element.src = images[num-1];
        document.getElementById("count").innerHTML = num.toString()+" / 13";
    }
}
function prev(){
    var element = document.getElementById("imgs");
    var num = Number(element.src.split("/").slice(-1)[0].split(".")[0]);
    if (num == 1){
        element.src = "img/13.jpg";
        document.getElementById("count").innerHTML = "13 / 13";
    } else {
        num--;
        element.src = images[num].src;
        document.getElementById("count").innerHTML = num.toString()+" / 13";
    }
}
function start(){
    window.timeout = setTimeout("next()", 3000);
    document.getElementById("player").src = "img/pause.png";
    document.getElementById("player").onclick = function(){ stop(); };
    document.getElementById("next_container").onclick = function(){ stop(); next(); start(); };
    document.getElementById("prev_container").onclick = function(){ stop(); prev(); start(); };
}
function stop(){
    clearTimeout(window.timeout);
    document.getElementById("player").src = "img/play.png";
    document.getElementById("player").onclick = function(){ start(); };
    document.getElementById("next_container").onclick = function(){ next(); };
    document.getElementById("prev_container").onclick = function(){ prev(); };
}

因为 onload 会为您加载的每个图像触发。显示它的例子。

function start() {
  console.log("I AM CALLED");
}

function loadNext () {
  document.querySelector("img").src = "http://placekitten.com/400/300"
}

window.setTimeout(loadNext, 2000);
<img src="http://placekitten.com/200/300" onload="start()" />

所以你调用 next(); start();,接下来更改源,这样它会导致 "onload="start()" 触发,然后你调用 start()。有你的两个计时器。在下一个和上一个调用之后删除 start()。