javascriptslideshowsetintervalsiema

Stop javascript slideshow which is autoplaying using setInterval - Siema


I'm using the siema slideshow because it seems super nice and lightweight.

I want the slideshow to play when the user hovers their mouse over, and stop when they leave.

I've got the play bit working - using setInterval() - as per the guide docs, but I can't get the slideshow to stop. I'm trying to kill the interval, but that doesn't seem to work.

Here's my full code

const mySiema = new Siema({
  duration: 250,
  loop: true, // note: this just gets the slideshow to return to the beginning
});

const container = document.querySelector('.siema');

var timer, intervalInSec = 1000;

container.addEventListener('mouseenter', () => setInterval(() => mySiema.next(), intervalInSec));

container.addEventListener('mouseleave', clearInterval(timer));

and heres a codepen for fiddling with.


Solution

  • You need to assign timer to the output of the setInterval() method.

    It (setInterval) returns an interval ID which uniquely identifies the interval, so you can remove it later by calling clearInterval()

    You also need to call an anonymous function on the mouse leave event to properly call clearInterval(). For example:

    container.addEventListener('mouseenter', () => timer = setInterval(() => mySiema.next(), intervalInSec));
    
    container.addEventListener('mouseleave', () => clearInterval(timer));