如何使用超时重置循环参数

时间:2018-09-20 01:33:44

标签: javascript for-loop settimeout

我试图每10毫秒运行一个函数,如果值达到某个阈值,则重新启动该函数。

如果有value > 10,我该如何再次开始for循环?

let x = 0
let ln = 12

function getValue() {
  // Returns an integer value
}

for (x; x <= ln; x++) {
  setTimeout(() => {
    getValue((value) => {
      if(value > 10) x = 0; // Restart for loop - doesn't seem to be working as intended
      if(x == 12) // do something else
    })
  }, 10)
}

1 个答案:

答案 0 :(得分:1)

我认为setInterval是实现这种目标的更好方法。如果计数器达到极限,则每次调用setInterval()时,请保持计数器递增,并用clearInterval清除间隔。如果满足其他条件,请将计数器重置为零:

let nums = [1, 2, 3, 12, 4, 1, 2, 4, 6, 3]
let i = 0
function getValue(fn){
    fn(nums[i % nums.length])
    i++
}

const MAX_ITERATIONS = 10

let iteration = 0
let int = setInterval(() => {
    getValue((value) => {
        if(value > 10) iteration = 0; // Reset the counter
        else iteration++
    })
    console.log("loop iteration: ", iteration)
    if (iteration >= MAX_ITERATIONS) clearInterval(int)
}, 1000)

MAX_ITERATIONS较低的情况下,它将到达循环结尾,然后第二次获得大于10的值并停止:

let nums = [1, 2, 3, 12, 4, 1, 2, 4, 6, 3]
let i = 0
function getValue(fn){
    fn(nums[i % nums.length])
    i++
}

const MAX_ITERATIONS = 4

let iteration = 0
let int = setInterval(() => {
    getValue((value) => {
        if(value > 10) iteration = 0; // Reset the counter
        else iteration++
    })
    console.log("loop iteration: ", iteration)
    if (iteration >= MAX_ITERATIONS) clearInterval(int)
}, 1000)