Javascript 更改SetInterval的间隔,而它为';她在跑步
我编写了一个javascript函数,它使用setInterval在一定的迭代次数内每隔十分之一秒操纵一个字符串Javascript 更改SetInterval的间隔,而它为';她在跑步,javascript,timer,setinterval,Javascript,Timer,Setinterval,我编写了一个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.flo
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() { ... }, 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);
我喜欢这个问题——激发了我内心的一个小小的计时器对象:
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);
一种更简单的方法是在刷新的函数中有一个
if
语句和一个控件以固定的时间间隔执行命令。在下面的示例中,我每2秒运行一次警报,间隔(intrv
)可以动态更改
var i=1;
var intrv=2; // << control this variable
var refreshId = setInterval(function() {
if(!(i%intrv)) {
alert('run!');
}
i++;
}, 1000);
var i=1;
变量intrv=2;// 您可以使用匿名函数:
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);
我问的问题和原来的海报一样,我这样做是为了解决问题。不知道这有多高效
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()
}
我也无法同步和更改设置间隔的速度,我正要发布一个问题。但我想我找到了一个方法。它当然应该改进,因为我是初学者。因此,我很高兴看到你对这件事的评论
<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>
0
第二个计数器停止
暂停
正常速度
速度x2
速度x4
启动第二定时器
var count1=0,
count2=0,
绿灯=新布尔值(0),//阻塞第二个计数器
速度=1000,//1秒
计数速度;
函数foo(){
countingSpeed=setInterval(函数(){
计数器1();
计数器2();
},速度);
}
函数计数器1(){
count1++;
document.getElementById(“count1”).innerHTML=count1;
}
函数计数器2(){
如果(绿灯!=假){
count2++;
document.getElementById(“count2”).innerHTML=count2;
}
}
函数startTimer2(){
//未单击按钮时,绿灯布尔值为false
//因此,第二定时器被阻断
绿灯=真;
计数器2();
//计数器2()亮起绿灯
}
//这些功能可修改计数器的速度
函数speed0(){
清除间隔(计数速度);
}
功能speedx(a){
清除间隔(计数速度);
速度=1000/a;
foo();
}
如果希望加载页面后计数器开始增加,请在调用countingSpeed
之前,将counter1()
和counter2()
放入foo()
。否则,执行前需要speed
毫秒。
编辑:较短的答案。简单的答案是,您不能更新已经创建的计时器的间隔。(只有两个函数setInterval/setTimer
和clearInterval/clearTimer
,因此拥有timerId
只能将其停用。)但您可以采取一些变通办法。看看。这是我的方法,我使用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();
这可以根据您的需要启动。超时是我用来让它保持在一个小时的顶端的方法
我需要每小时开始一个小时的代码块。因此,这将从服务器启动时开始,每小时运行一次。基本上,初始运行是在同一分钟内开始间歇。所以在init的一秒钟内,立即运行,然后每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()
这里我们第一次运行,然后每小时运行一次。我是javascript的初学者,在前面的答案中没有找到任何帮助(但有很多好主意)。
下面的这段代码加速(加速度>1)或减速(加速度
无法获取任何较短的创建新功能:
// 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();
}
受上述内部回调的启发,我制作了一个函数,以分钟为单位触发回调。如果超时设置为6000、15000、30000、60000等间隔,它将持续同步调整间隔,以精确转换到系统时钟的下一分钟
//Interval timer to trigger on even minute intervals
function setIntervalSynced(callback, intervalMs) {
//Calculate time to next modulus timer event
var betterInterval = function () {
var d = new Date();
var millis = (d.getMinutes() * 60 + d.getSeconds()) * 1000 + d.getMilliseconds();
return intervalMs - millis % intervalMs;
};
//Internal callback
var internalCallback = function () {
return function () {
setTimeout(internalCallback, betterInterval());
callback();
}
}();
//Initial call to start internal callback
setTimeout(internalCallback, betterInterval());
};
您可以使用变量并更改变量
````setInterval([函数],[变量])`通过回调,你是说函数的最后一行用setTimeout(…,newInterval)递归调用自己吗?我想这就是他的意思。我刚刚试过,它似乎起作用了。谢谢,伙计们!只给出了9个hi:)--t
可能应该是t--
递归地执行此操作如果次数过大,是否会有导致堆栈溢出错误的风险?这里很挑剔,但我必须说,代码很难阅读。如果要使用下一行大括号,至少要有礼貌地使用4-8空格缩进,或者不要超过2个缩进。IMO更容易阅读。还要注意将t
重命名为tick
,这是我对“t”代表什么的最好猜测t
是一个非常糟糕的变量名。谢谢-让我朝着正确的方向前进,因为我正在做类似的事情。简单而有效。谢谢我更喜欢这个答案,因为它实际上回答了OP(和我的)问题。setTimeout可能会被延迟(由100%的cpu使用、其他脚本等造成),而as setInterval不受这些延迟的影响——这使得它在“实时”方面具有更高的优势。我99%确信您关于setInterval
的说法是错误的@RozzA-它是
(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();
}
//Interval timer to trigger on even minute intervals
function setIntervalSynced(callback, intervalMs) {
//Calculate time to next modulus timer event
var betterInterval = function () {
var d = new Date();
var millis = (d.getMinutes() * 60 + d.getSeconds()) * 1000 + d.getMilliseconds();
return intervalMs - millis % intervalMs;
};
//Internal callback
var internalCallback = function () {
return function () {
setTimeout(internalCallback, betterInterval());
callback();
}
}();
//Initial call to start internal callback
setTimeout(internalCallback, betterInterval());
};