javascriptloopscarouselcontinuous

JavaScript: I need a continuous loop that won't kill the browser or block the page


I have a carousel plugin I've created and I need a way to have it run a function that moves the image to the side and brings in the next image. I have this working with navigation arrows but I want to implement a way for it to do this on its own.

I'm having trouble finding information on this as Google is bloated with everyone's carousel libraries.

Basically, I just need something like:

window.setTimeout(() => {
  // do something
}, 1000);

But it needs to run over and over unless a particular event is triggered. My first thought was a while loop but that would have been disastrous.

I don't have much to show but currently, this is the code:

  let mouseIsOver = false;

  inner.addEventListener('mouseenter', () => {
    mouseIsOver = true;

    console.log(mouseIsOver);
  });

  inner.addEventListener('mouseleave', () => {
    mouseIsOver = false;

    console.log(mouseIsOver);
  });

Solution

  • You could use the setInterval method which repeatedly calls a function. And then call clearInterval to stop it.

    const inner = document.getElementById('inner');
    const pages = ['mediumspringgreen', 'coral', 'cyan', 'moccasin'];
    let interval = start();
    let i = 0;
    
    function start() {
        return setInterval(() => inner.style.background = pages[i++ % 4], 3000);
    }
    
    inner.addEventListener('mouseenter', () => {
      clearInterval(interval);
      console.log('pause');
    });
    
    inner.addEventListener('mouseleave', () => {
      interval = start();
      console.log('continue');
    });
    #inner { width: 100px; height: 100px; background: cyan }
    .as-console-wrapper { max-height: 1.5em !important; }
    <div id=inner></div>