幻灯片 javascript play/pause 按钮

Slideshow javascript play/pause button

我正在使用 play/pause 按钮在 Javascript 中制作幻灯片。当我按一次按钮时,幻灯片开始播放。当我第二次按下时,幻灯片必须停止。我只是不知道如何把这个功能放在一个按钮上。

这是我的代码:

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8" />
    <title>Oefening 19.7</title>
    <link href="stijl_Oefening19_6.css" rel="stylesheet" />
    <script>
    var i = 0;
    var foto = new Array(3);
    var timer;

    foto[0] = "images/slideshow/slideshow1.png";
    foto[1] = "images/slideshow/slideshow2.png";
    foto[2] = "images/slideshow/slideshow3.png";
    foto[3] = "images/slideshow/slideshow4.png";

    function slide() {

            document.getElementById("slideshow").src = foto[i];

            if (i < foto.length - 1) i++;
            else i = 0;

            timer = setTimeout("slide()", 3000);
    }
    </script>
</head>

<body>
    <div id="portfolio">
        <img src="images/slideshow/slideshow1.png" id="slideshow" alt="slideshow" />
    </div>
    <div id="button">
        <a href="#" id="startcycle" onclick="slide()">
            <img id="btnCycle" src="images/slideshow/cyclebutton.png" />
        </a>
    </div>
</body>

</html>

改为使用 setInterval()。并将开关功能和滑动功能分开。

function slide() {
    document.getElementById("slideshow").src = foto[i];
    i = (i + 1)%foto.length;
}
function setTimer(){
    if (timer) {
       // stop 
       clearInterval( timer );
       timer=null;
    }
    else {
       timer = setInterval("slide()",1000);
    }
}

让按钮调用setTimer()。