JavaScript setInterval() 方法无法按我的预期工作

标签 javascript loops

我有一个错误字符串数组,这些错误是提交后表单中的错误。

我想在固定时间后将这些错误一一显示为通知,假设每 5 秒一次。

我的代码是:

var array = ["1", "2", "3", "4", "5", "6"];
recursive();

function recursive() {
  var error = array.pop();
  if (typeof error === 'undefined') {
    return;
  } else {
    console.log(error);
    //         showNoti(error);
  }
  setInterval(function() {
    recursive()
  }, 5000);
}

此代码的问题在于,它在前 2 次迭代中运行良好,在 5 秒后打印出 5,打印出 6。

但在第三次迭代时,它同时打印字符串 4 和 3。与第四次迭代类似。

如何修复它,使其每 5 秒打印一次数组中的每个元素?

最佳答案

目前,每次递归调用都在初始化另一个间隔。因此,例如,在第一次调用之后,将运行一个间隔:在第二次调用之后,将初始化另一个间隔(两个间隔),等等。

setInterval 放在 recursive 之外:

var array = ["1", "2", "3", "4", "5", "6"];
recursive();

function recursive() {
  var error = array.pop();
  if (typeof error === 'undefined') {
    return;
  } else {
    console.log(error);
    //         showNoti(error);
  }
}
setInterval(function() {
  recursive()
}, 500);

或者使用setTimeout代替:

var array = ["1", "2", "3", "4", "5", "6"];
recursive();

function recursive() {
  var error = array.pop();
  if (typeof error === 'undefined') {
    return;
  } else {
    console.log(error);
    //         showNoti(error);
  }
  setTimeout(recursive, 500);
}

关于JavaScript setInterval() 方法无法按我的预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54822733/

相关文章:

javascript - 用javascript计算Wifi RSSI信号距离的方法

javascript - Redux:将 `reducres` 与非平坦状态结合起来,避免创建大量 reducer

python - 列表索引超出范围 - Python 索引错误

Java 菜单循环无限重复

VBA 用公式填充多个工作表上的单元格

javascript - 查找数组项的最长长度 - JS

javascript - Node.js Mongoose 类型错误 : set is not a function

javascript - 文件读取器 API : viewing the contents outside of a callback

java - 字符串中所有字符出现的索引

r - 在每次函数迭代时动态更新输入数据帧,无需全局分配