javascript - 无法停止 slider

标签 javascript

尝试制作最简单的画廊。有一个按钮可以将图像变成<button class = "play-pause">Play</ button> 。点击它开始setInterval ,但再次按下时需要停止。如何做到这一点?

这是沙箱的链接:http://jsfiddle.net/eL31q3eq/

我的尝试:

document.querySelector('.play-pause').addEventListener('click', function() {
    if(timer == null) clearInterval(timer);

    this.innerHTML = "Pause";

    timer = setInterval(function() {
        i = (i < images.length - 1) ? ++i : 0;
        img.src = images[i];
    }, 1000);

    timer = null;
});

最佳答案

您正在丢弃停止幻灯片放映所需的变量 - 此处的解决方案。

http://jsfiddle.net/obh5tanL/

也不要初始化计时器变量。

document.querySelector('.play-pause').addEventListener('click', function() {
    if (timer) {
        clearInterval(timer);
        this.innerHTML = "Play";
    }
    else {
        this.innerHTML = "Pause";

        timer = setInterval(function() {
            i = (i < images.length - 1) ? ++i : 0;
            img.src = images[i];
        }, 1000);
    }

});

关于javascript - 无法停止 slider ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29379260/

相关文章:

javascript - 带有 html 输入控件的动态生成的表行在回发时消失

javascript - 如何从本地存储重新加载 jstree?

javascript - 如何用 pie div 元素创建一个圆圈?

javascript - Firefox 不喜欢 jquery 中的 .val?

javascript - 如何通知我的应用程序正在接收来自 Service Worker 的缓存响应?

javascript - 有多个对等点 PeerJS?

javascript - HTML5 Canvas ,使用 jspdf.js 将 Canvas 转换为 PDF

javascript - 在 Ajax xhr 响应上使用 jQuery.filter 和 jQuery.find 时的不同结果

javascript - React,为什么要用 Redux

javascript - 如何在运行 Node.js 应用程序之前确保 MySQL 数据库存在