質問

I have a rotating slider on a website that I am working on.

the slider automatically scrolls when the page is loaded, and is supposed to stop when it is moused over, and then start again when the mouse leaves.

I have the stopping of the slider working, but when i mouse out, the slider starts up again, but twice as fast, causing the slider to show no content.

Is there some reason why my clear interval is not working correctly? how can i get the slider to stop and start without it changing speed and messing up?

     rotateSwitch: function() {  
       var myTimer=setInterval(function() { this.autoRotate(); }.bind(this), 5000);
       $('.hero img').hover(
         function() {
         window.clearInterval(myTimer)},
         function() {
         this.rotateSwitch();}.bind(this));
    },       
役に立ちましたか?

解決

On every mouseleave you bind the function again by calling this.rotateSwitch(). Instead, only start the interval again:

rotateSwitch: function() {  
    var myTimer,
        that = this;
    function start() {
        myTimer = setInterval(that.autoRotate.bind(that), 5000);
    }
    function stop() {
        clearInterval(myTimer);
    }
    $('.hero img').hover(stop, start);
    start();
},

If that function is called multiple times, you might want to restrict your .hero img selector to a specific context as well.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top