clearTimeout() not working

谁说我不能喝 提交于 2019-12-05 11:31:25

The clearTimeout is working, but you are immediately re-setting it in the same method. So it starts up again right away. You need to conditionally check for whether to start it:

slideshow: function(sw) {
    var timer;

    if (sw == "off") {
        clearTimeout(timer);
    } else {
        timer = setTimeout(function() { Gallery.next(); }, 1000);
    }
}

The way you structured your code is more complex than it needs to be and has a few bugs. I'd recommend restructuring it like this:

var Gallery = {
    timer: null,

    next: function() {
        /* do stuff */
    },

    close: function() {
        if (Gallery.timer) {
            clearInterval(Gallery.timer);
            Gallery.timer = null;
        }
    },

    slideshow: function() {
        Gallery.close();
        Gallery.timer = setInterval(function() {
            Gallery.next();
        }, 1000);
    }
}

You'd start the slideshow with Gallery.slideshow(); and stop it with Gallery.close();

that would be because you are re-setting the timeout after you have cleared it. Rethink the order of your code.

Every time you call the slideshow function, the setTimeout gets executed indipendently of the sw variable being "off" or not.

slideshow: function(sw)
   {
   if (sw == "off") {
      clearTimeout(timer);
   } else {
      var timer = setTimeout(function() {Gallery.next();Gallery.slideshow();}, 1000);
   }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!