在运行时更改setInterval的间隔
-
16-09-2019 - |
题
我编写了一个JavaScript函数,该功能使用setInterval来操纵一秒钟的每秒钟,以进行一定数量的迭代。
function timer() {
var section = document.getElementById('txt').value;
var len = section.length;
var rands = new Array();
for (i=0; i<len; i++) {
rands.push(Math.floor(Math.random()*len));
};
var counter = 0
var interval = setInterval(function() {
var letters = section.split('');
for (j=0; j < len; j++) {
if (counter < rands[j]) {
letters[j] = Math.floor(Math.random()*9);
};
};
document.getElementById('txt').value = letters.join('');
counter++
if (counter > rands.max()) {
clearInterval(interval);
}
}, 100);
};
我不想将间隔设置为特定数字,而是想根据计数器进行每次运行时进行更新。因此,而不是:
var interval = setInterval(function() { ... }, 100);
这将是:
var interval = setInterval(function() { ... }, 10*counter);
不幸的是,这无效。看起来“ 10*计数器”等于0。
那么,如何每次匿名函数运行时如何调整间隔?
解决方案
利用 setTimeout()
反而。然后,回调将负责触发下一个超时,此时您可以增加或以其他方式操纵时间安排。
编辑
这是一个通用函数,您可以用于为任何功能调用应用“减速”超时。
function setDeceleratingTimeout(callback, factor, times)
{
var internalCallback = function(tick, counter) {
return function() {
if (--tick >= 0) {
window.setTimeout(internalCallback, ++counter * factor);
callback();
}
}
}(times, 0);
window.setTimeout(internalCallback, factor);
};
// console.log() requires firebug
setDeceleratingTimeout(function(){ console.log('hi'); }, 10, 10);
setDeceleratingTimeout(function(){ console.log('bye'); }, 100, 10);
其他提示
您可以使用匿名函数:
var counter = 10;
var myFunction = function(){
clearInterval(interval);
counter *= 10;
interval = setInterval(myFunction, counter);
}
var interval = setInterval(myFunction, counter);
更新:正如A. Wolff所建议的,使用 setTimeout
避免需要 clearInterval
.
var counter = 10;
var myFunction = function() {
counter *= 10;
setTimeout(myFunction, counter);
}
setTimeout(myFunction, counter);
我喜欢这个问题 - 启发了我的一个小计时对象:
window.setVariableInterval = function(callbackFunc, timing) {
var variableInterval = {
interval: timing,
callback: callbackFunc,
stopped: false,
runLoop: function() {
if (variableInterval.stopped) return;
var result = variableInterval.callback.call(variableInterval);
if (typeof result == 'number')
{
if (result === 0) return;
variableInterval.interval = result;
}
variableInterval.loop();
},
stop: function() {
this.stopped = true;
window.clearTimeout(this.timeout);
},
start: function() {
this.stopped = false;
return this.loop();
},
loop: function() {
this.timeout = window.setTimeout(this.runLoop, this.interval);
return this;
}
};
return variableInterval.start();
};
示例使用
var vi = setVariableInterval(function() {
// this is the variableInterval - so we can change/get the interval here:
var interval = this.interval;
// print it for the hell of it
console.log(interval);
// we can stop ourselves.
if (interval>4000) this.stop();
// we could return a new interval after doing something
return interval + 100;
}, 100);
// we can change the interval down here too
setTimeout(function() {
vi.interval = 3500;
}, 1000);
// or tell it to start back up in a minute
setTimeout(function() {
vi.interval = 100;
vi.start();
}, 60000);
我有与原始海报相同的问题,这是解决方案的。不确定这有多高度。
interval = 5000; // initial condition
var run = setInterval(request , interval); // start setInterval as "run"
function request() {
console.log(interval); // firebug or chrome log
clearInterval(run); // stop the setInterval()
// dynamically change the run interval
if(interval>200 ){
interval = interval*.8;
}else{
interval = interval*1.2;
}
run = setInterval(request, interval); // start the setInterval()
}
这是我这样做的方式,我使用settimeout:
var timer = {
running: false,
iv: 5000,
timeout: false,
cb : function(){},
start : function(cb,iv){
var elm = this;
clearInterval(this.timeout);
this.running = true;
if(cb) this.cb = cb;
if(iv) this.iv = iv;
this.timeout = setTimeout(function(){elm.execute(elm)}, this.iv);
},
execute : function(e){
if(!e.running) return false;
e.cb();
e.start();
},
stop : function(){
this.running = false;
},
set_interval : function(iv){
clearInterval(this.timeout);
this.start(false, iv);
}
};
用法:
timer.start(function(){
console.debug('go');
}, 2000);
timer.set_interval(500);
timer.stop();
一种简单的方法是拥有一个 if
在刷新功能和控件中进行声明,以定期执行您的命令。在下面的示例中,我每2秒钟运行一次警报和间隔(intrv
)可以动态更改...
var i=1;
var intrv=2; // << control this variable
var refreshId = setInterval(function() {
if(!(i%intrv)) {
alert('run!');
}
i++;
}, 1000);
简单的答案是 您无法更新已经创建的计时器的间隔. 。 (只有两个功能 setInterval/setTimer
和 clearInterval/clearTimer
, ,所以有一个 timerId
您只能停用它。)但是您可以进行一些解决方法。看一眼 这个github回购.
可以根据需要启动这一点。超时是我用来将其保持在小时顶部的方法。
我每小时都需要在小时开始一个代码块。因此,这将从服务器启动开始并每小时运行间隔。基本的初始运行是在同一分钟内开始间隔。因此,在从初始化的一秒钟内,立即在每5秒钟内立即运行。
var interval = 1000;
var timing =function(){
var timer = setInterval(function(){
console.log(interval);
if(interval == 1000){ /*interval you dont want anymore or increment/decrement */
interval = 3600000; /* Increment you do want for timer */
clearInterval(timer);
timing();
}
},interval);
}
timing();
或者,如果您只想在开始时发生某些事情,然后以特定的间隔永远发生某些事情,您可以与SetInterval同时称呼它。例如:
var this = function(){
//do
}
setInterval(function(){
this()
},3600000)
this()
在这里,我们第一次进行此操作。
我也无法同步并改变我的setIntervals的速度,我正要发布一个问题。但是我想我找到了一种方法。当然应该改进它,因为我是初学者。因此,我很乐意阅读您对此的评论/评论。
<body onload="foo()">
<div id="count1">0</div>
<div id="count2">2nd counter is stopped</div>
<button onclick="speed0()">pause</button>
<button onclick="speedx(1)">normal speed</button>
<button onclick="speedx(2)">speed x2</button>
<button onclick="speedx(4)">speed x4</button>
<button onclick="startTimer2()">Start second timer</button>
</body>
<script>
var count1 = 0,
count2 = 0,
greenlight = new Boolean(0), //blocks 2nd counter
speed = 1000, //1second
countingSpeed;
function foo(){
countingSpeed = setInterval(function(){
counter1();
counter2();
},speed);
}
function counter1(){
count1++;
document.getElementById("count1").innerHTML=count1;
}
function counter2(){
if (greenlight != false) {
count2++;
document.getElementById("count2").innerHTML=count2;
}
}
function startTimer2(){
//while the button hasn't been clicked, greenlight boolean is false
//thus, the 2nd timer is blocked
greenlight = true;
counter2();
//counter2() is greenlighted
}
//these functions modify the speed of the counters
function speed0(){
clearInterval(countingSpeed);
}
function speedx(a){
clearInterval(countingSpeed);
speed=1000/a;
foo();
}
</script>
如果您希望计数器一旦加载页面开始增加,请放置 counter1()
和 counter2()
在 foo()
前 countingSpeed
叫做。否则,它需要 speed
执行前毫秒。编辑:较短的答案。
我是JavaScript的初学者,在以前的答案中没有找到任何帮助(但很多好主意)。
下面的这段代码加速(加速度> 1)或减速(加速度<1)。我希望它可以帮助某些人:
function accelerate(yourfunction, timer, refresh, acceleration) {
var new_timer = timer / acceleration;
var refresh_init = refresh;//save this user defined value
if (refresh < new_timer ){//avoid reseting the interval before it has produced anything.
refresh = new_timer + 1 ;
};
var lastInter = setInterval(yourfunction, new_timer);
console.log("timer:", new_timer);
function stopLastInter() {
clearInterval(lastInter);
accelerate(yourfunction, new_timer, refresh_init, acceleration);
console.log("refresh:", refresh);
};
setTimeout(stopLastInter, refresh);
}
和 :
timer
: :MS中的SetInterval初始值(增加或减少)refresh
: :新价值之前的时间timer
计算。这是 步骤lenghtfactor
: :旧与下一个之间的差距timer
价值。这是 阶跃高度
(function variableInterval() {
//whatever needs to be done
interval *= 2; //deal with your interval
setTimeout(variableInterval, interval);
//whatever needs to be done
})();
无法缩短
制作新功能:
// set Time interval
$("3000,18000").Multitimeout();
jQuery.fn.extend({
Multitimeout: function () {
var res = this.selector.split(",");
$.each(res, function (index, val) { setTimeout(function () {
//...Call function
temp();
}, val); });
return true;
}
});
function temp()
{
alert();
}
这是创建减速/加速间隔计时器的另一种方法。间隔将乘以一个因子,直到超过总时间为止。
function setChangingInterval(callback, startInterval, factor, totalTime) {
let remainingTime = totalTime;
let interval = startInterval;
const internalTimer = () => {
remainingTime -= interval ;
interval *= factor;
if (remainingTime >= 0) {
setTimeout(internalTimer, interval);
callback();
}
};
internalTimer();
}
var counter = 15;
var interval = setTimeout(function(){
// your interval code here
window.counter = dynamicValue;
interval();
}, counter);