简体   繁体   中英

How do I properly restart a timeout in Javascript?

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 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);
}

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);
});

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
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM