我需要在javascript中有一个永无止境的循环。这几乎就像设定的间隔。但是对于每个循环,需要动态应用时间延迟。每个循环的延迟值都会发生变化。那么有可能在使用某种睡眠功能时使用吗?或者是否可以更改每次迭代的设置间隔时间?
以下代码没有给出延迟。始终采用给定的第一个值。
<script>
var someTimeoutVar = 1000;
var inc = 1;
setInterval(function() {
inc++;
someTimeoutVar = inc * 1000;
console.log(someTimeoutVar);
}, someTimeoutVar)
</script>
答案 0 :(得分:5)
使用setTimeout代替并保持递归调用。
function someLoop() {
var nextExecutionTime = calc();
setTimeout(someLoop, nextExecutionTime);
}
答案 1 :(得分:0)
您可以使用:
setInterval(expression, someTimeoutVar);
然后根据需要更改someTimeoutVar
答案 2 :(得分:0)
function repeatedOperation() {
/* Do operations here. */
/* ... */
/* You can return something if desired to help
* the other function decide what the new timeout
* delay should be. By default, I have set the new
* timeout delay to be whatever is returned here
* plus a random fuzz time between 0-1 second. */
return 1; /* interpreted as milliseconds */
}
function updateTimeout(result) {
/* Compute new timeout value here based on the
* result returned by the operation.
* You can use whatever calculation here that you want.
* I don't know how you want to decide upon a new
* timeout value, so I am just giving a random
* example that calculates a new time out value
* based on the return value of the repeated operation
* plus an additional random number. */
return Math.round(result + 1000*Math.random());
/* This might have been NaN. We'll deal with that later. */
}
function proxyInterval(oper, delay) {
var timeout = delay(oper());
setTimeout(function() { proxyInterval(oper, delay); }, timeout-0 || 1000);
/* Note: timeout-0 || 1000 is just in case a non-numeric
* timeout was returned by the operation. We also
* could use a "try" statement, but that would make
* debugging a bad repeated operation more difficult. */
}
/* This is how to use the above code: */
proxyInterval(repeatedOperation, updateTimeout);