如何一次设置多个超时 运行?
How do I have multiple set timeouts running at once?
这更多的是关于我应该如何解决我的问题的问题,而不是使用什么代码。这是我的代码的一般 framework/simplification。如果需要,我可以提供实际代码。问题在下面,它类似于我问的最后一个问题,因为它是无法正常工作的同一系统的一部分:
for (i = 0; i < 10; i++) {
var amt = 0;
function checktime() {
console.log(amt + " / " + i);
amt++;
if (amt <= 5) {
setTimeout(checktime, 3000);
}
}
checktime();
}
我希望它为每个 i 立即设置所有超时 运行。控制台结果
0 / 0
0 / 1
0 / 2
...
0 / 8
0 / 9
1 / 10
2 / 10
3 / 10
4 / 10
...
13 / 10
14 / 10
我希望它看起来像这样:
0/0
0/1
0/2
0/3
...
0/9
1/0
1/1
...
5/9
5/10
抱歉问了这么长的问题,但我该怎么做呢?
在 checktime 中有一个运行循环的函数。设置变量,然后使用 setTimout
.
再次将 count
变量传递到内部函数中
function checktime() {
// Set the amt variable to zero
let amt = 0;
// Set count to zero if it doesn't exist
function loop(count = 0) {
// Log the new data
console.log(`${amt}/${count}`);
// Increase the count
++count;
// If count hits 10 reset the count
// and increase the amt variable
if (count === 10) {
count = 0;
++amt;
}
// Call the loop function again and pass in the new count
// as a parameter
setTimeout(loop, 1000, count);
}
loop();
}
checktime();
有两种方法可以做到这一点。
- 像这样使用嵌套循环
for(i = 0; i< 10; i++){
for(j = 0; j < 5; j++) {
console.log(i + " / " + j)
setTimeout(3000)
}
}
- 像这样使用递归:
function setTimeout_recurse(amt, i) {
if (amt < 5) {
console.log(i + " / " + amt)
amt ++;
setTimeout(3000)
setTimeout_recurse(amt, i)
}
}
for(i = 0; i< 10; i++){
var amt = 0;
setTimeout_recurse(amt, i);
}
您会注意到基数现在是 i
而不是 amt
,这更有意义作为基数。
这更多的是关于我应该如何解决我的问题的问题,而不是使用什么代码。这是我的代码的一般 framework/simplification。如果需要,我可以提供实际代码。问题在下面,它类似于我问的最后一个问题,因为它是无法正常工作的同一系统的一部分:
for (i = 0; i < 10; i++) {
var amt = 0;
function checktime() {
console.log(amt + " / " + i);
amt++;
if (amt <= 5) {
setTimeout(checktime, 3000);
}
}
checktime();
}
我希望它为每个 i 立即设置所有超时 运行。控制台结果 0 / 0
0 / 1
0 / 2
...
0 / 8
0 / 9
1 / 10
2 / 10
3 / 10
4 / 10
...
13 / 10
14 / 10
我希望它看起来像这样:
0/0
0/1
0/2
0/3
...
0/9
1/0
1/1
...
5/9
5/10
抱歉问了这么长的问题,但我该怎么做呢?
在 checktime 中有一个运行循环的函数。设置变量,然后使用 setTimout
.
count
变量传递到内部函数中
function checktime() {
// Set the amt variable to zero
let amt = 0;
// Set count to zero if it doesn't exist
function loop(count = 0) {
// Log the new data
console.log(`${amt}/${count}`);
// Increase the count
++count;
// If count hits 10 reset the count
// and increase the amt variable
if (count === 10) {
count = 0;
++amt;
}
// Call the loop function again and pass in the new count
// as a parameter
setTimeout(loop, 1000, count);
}
loop();
}
checktime();
有两种方法可以做到这一点。
- 像这样使用嵌套循环
for(i = 0; i< 10; i++){
for(j = 0; j < 5; j++) {
console.log(i + " / " + j)
setTimeout(3000)
}
}
- 像这样使用递归:
function setTimeout_recurse(amt, i) {
if (amt < 5) {
console.log(i + " / " + amt)
amt ++;
setTimeout(3000)
setTimeout_recurse(amt, i)
}
}
for(i = 0; i< 10; i++){
var amt = 0;
setTimeout_recurse(amt, i);
}
您会注意到基数现在是 i
而不是 amt
,这更有意义作为基数。