简体   繁体   English

您可以在运行时更新 setInterval 变量吗

[英]Can you update setInterval variable while it runs

I need to modify existing slider.我需要修改现有的 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.现在我需要在每次迭代时更新 slidePause 变量。 Looking for an example if its possible.如果可能的话,寻找一个例子。

No: You cannot do it with setInterval .不:你不能用setInterval来做。 Once it is set, it may only be cancelled.一旦设置,它只能被取消。

What you can do however, is use setTimeout to achieve your goals.但是,您可以做的是使用setTimeout来实现您的目标。 While this can be done recursively, I prefer to take advantage of promises to do it iteratively:虽然这可以递归地完成,但我更喜欢利用 Promise 来迭代地完成它:

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

One of the problems with setInterval() is that JavaScript's single threaded nature can result in uneven periods between the setInterval() code being fired. setInterval()的问题之一是 JavaScript 的单线程特性可能导致setInterval()代码被触发之间的不均匀周期。 To avoid this, run setInterval() at a faster rate, and calculate the time passed to determine whether an action should be taken.为避免这种情况,请以更快的速度运行setInterval() ,并计算经过的时间以确定是否应采取行动。

If you make the calculation for time passed dependent on a variable you can change the effective rate at which the event occurs.如果您根据变量计算经过的时间,您可以更改事件发生的有效速率。

 function nextSlide(period){ console.log("Next Slide in "+period); } function VariableTimer(period, startImmediately = true) { this.period = period; self = this; this.startTime = startImmediately?0:Date.now(); this.time = setInterval(function(){ if (Date.now()-self.startTime > self.period*1000) { self.startTime = Date.now(); nextSlide(self.period); } }, 100); // Run setInterval at 100ms intervals. this.stop = function(){ clearInterval(self.time); } } let timer = new VariableTimer(10); // Change the timer period like this // timer.period = 5; // After 20 seconds switch to 5 second intervals setTimeout(function(){timer.period = 5;},20000); // After 40 seconds, stop the timer. setTimeout(function(){timer.stop();console.log("timer stopped")}, 40000);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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