MasterNone
MasterNone

Reputation: 568

Can you update setInterval variable while it runs

I need to modify existing slider. Its slides now have differing data-seconds added to it and need be active that long. Previously I had:

var slidePause = 10;
function startSlideBanner() {
  bannerTimer = setInterval(nextSlide, slidePause * 1000);
}
startSlideBanner();

Which worked infinitely well. Now I would need to update slidePause variable every iteration. Looking for an example if its possible.

Upvotes: 1

Views: 803

Answers (1)

Slava Knyazev
Slava Knyazev

Reputation: 6081

No: You cannot do it with setInterval. Once it is set, it may only be cancelled.

What you can do however, is use setTimeout to achieve your goals. While this can be done recursively, I prefer to take advantage of promises to do it iteratively:

const wait = ms => new Promise(res => setTimeout(res, ms));
let slidePause = 10;

async function startSlideBanner() {
   while(true) {
     await wait(slidePause * 1000);
     nextSlide();
     
     // Example: Double the time for each slide
     slidePause = slidePause * 2;
   }
}

startSlideBanner();

Upvotes: 2

Related Questions