代码之家  ›  专栏  ›  技术社区  ›  Trung Bún

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

  •  0
  • Trung Bún  · 技术社区  · 6 年前

    我拥有的代码是:

    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秒钟打印一次数组中的每个元素?

    4 回复  |  直到 6 年前
        1
  •  3
  •   CertainPerformance    6 年前

    目前,每个 recursive 正在初始化 间隔因此,例如,在第一次调用之后,将运行一个间隔:在第二次调用之后,将初始化另一个间隔(两个间隔),以此类推。

    setInterval 外面 相反:

    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);
    }
        2
  •  2
  •   adiga    6 年前

    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(recursive, 5000);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        3
  •  1
  •   fdomn-m    6 年前

    setInterval 将启动一个无限重复的计时器。在这种情况下,您可以控制是否希望它在代码中重复。

    这就是“setTimeout”的含义——一次延迟执行。

    设定间隔 setTimeout

    var array = ["1", "2", "3", "4", "5", "6"];
    recursive();
    
    function recursive() {
      var error = array.pop();
      if (typeof error === 'undefined') {
        return;
      } 
      console.log(error);
      setTimeout(function() {
        recursive()
      }, 5000);
    }
    
        4
  •  1
  •   Vikas    6 年前

    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);
      }
    }
     setInterval(function() {
        recursive()
      }, 5000);