admin 管理员组

文章数量: 1086019

I have a carousel of slides that I am rotating through at 5 second intervals. I have a function that clears the timeout to stop the rotation. I am trying to restart the carousel with the code below. The behavior works but incorrectly. Instead of resuming at 5 sec intervals it is quickly flashing through the slides.

t = setTimeout(carousel, 5000); 
var interval;
$(document).on('mousemove keyup keypress',function(){
    clearTimeout(carousel);
    setTimeout(carousel, 6000);
})

I have a carousel of slides that I am rotating through at 5 second intervals. I have a function that clears the timeout to stop the rotation. I am trying to restart the carousel with the code below. The behavior works but incorrectly. Instead of resuming at 5 sec intervals it is quickly flashing through the slides.

t = setTimeout(carousel, 5000); 
var interval;
$(document).on('mousemove keyup keypress',function(){
    clearTimeout(carousel);
    setTimeout(carousel, 6000);
})
Share Improve this question asked Apr 18, 2019 at 18:48 KevMoeKevMoe 4434 silver badges21 bronze badges 1
  • 2 You need to use clearTimeout(t). t is an identifier for the timer. This is what you cancel, not the function carousel. – snwflk Commented Apr 18, 2019 at 18:53
Add a ment  | 

3 Answers 3

Reset to default 4

I think you are clearing timeout on inproper variable. According to the docs it should be id of timeout so:

t = setTimeout(carousel, 5000); 
$(document).on('mousemove keyup keypress',function(){
    clearTimeout(t);
    t = setTimeout(carousel, 6000);
}

Here's the problem:

t = setTimeout(carousel, 5000); 
var interval;
$(document).on('mousemove keyup keypress',function(){
    clearTimeout(t /* instead of carousel */);
    t = setTimeout(carousel, 6000); // also refresh the value of the timeout
})

This

    clearTimeout(carousel);

is incorrect. clearTimeout's argument isn't the callback function, it's the timeout's identifier returned by setTimeout. Should be something like

t = setTimeout(carousel, 5000); 

$(document).on(/* some events */,function(){
    clearTimeout(t);
});

$(document).on(/* some other events */,function(){
    t = setTimeout(carousel, 6000);
});

本文标签: How do I properly restart a timeout in JavascriptStack Overflow