setInterval具有不同的持续时间
问题描述:
下面的代码启动幻灯片放映循环。当幻灯片的第一个循环完成时,我想在第一个幻灯片上暂停6000ms。在这种情况下,我希望能够将时间添加为6000ms而不是1000ms。setInterval具有不同的持续时间
this.isPlaying = setInterval(function(){
self._change(null, "-=", null, self.lineScrollDo, null);
}, 1000);
答
使用的setTimeout代替的setInterval的:
var _this = this;
(function(){
function next(){
self._change(null, "-=", null, self.lineScrollDo, null);
var duration = 1000;
if(/* cond */)
duration = 6000;
_this.isPlaying = setTimeout(next, duration);
}
_this.isPlaying = setTimeout(next, 1000);
})();
答
与setInterval
方法保持一致,不同的方法可能只是使用计数器。
(function(){
var counts = 0, target = 6, self = /* Refer to your object here */;
self.isPlaying = setInterval(function(){
if (++counts === target) {
self._change(null, "-=", null, self.lineScrollDo, null);
target = target === 6 ? 1 : 6;
counts = 0;
}
}, 1000); /// <-- needs to be set at offset that will hit both 1 and 6 secs.
})();
显然,这样做的缺点是你获得更多的执行什么都不做,以及实现不同的时间偏移可能是棘手的,如果你不能找到一个共同点。但是资源的创造和破坏较少,并且将更容易将多个时间转换器链接在一起。
例如,你可以有一个堆栈跟踪的偏移量:
var counts = 0, targets = [6,1,2,4], target = targets.shift(), ...
然后,而不是使用:
target = target === 6 ? 1 : 6;
您使用:
targets.push(target);
target = targets.shift();
假设你想要一个循环的时间偏移模式,也就是说。
你必须停止间隔,将新的设置为6秒,停止它,然后回到1秒。你最好重构它不使用setInterval。或者可能包含已经具有此功能的幻灯片(cycle2) –