2个setInterval()实例正在运行,如何运行一个?

时间:2019-05-15 20:10:14

标签: javascript function variables setinterval

doubles setInterval()实例正在运行,如何运行一个实例?

var odo = document.querySelector(".odometer");
var ve = document.getElementById("viewers");
var input = document.querySelector("#inputUserName");

function handleEnter(e) {
  var keycode = e.keyCode ? e.keyCode : e.which;
  if (keycode == "13") {
    console.log("You pressed enter!");
    var identifiant = input.value;
    main(identifiant);
  }
}

function main(identifiant) {
  streamViewers(identifiant);

  function streamViewers(v) {
    var refreshV = setInterval(() => { // var refreshV is for stop the interval on bad response
      fetch(`https://api.twitch.tv/helix/streams?user_id=${v}`, {
        headers: {
          "client-id": "0ikjx4yg4ifvnm010hu1p5w8c4pjgm"
        }
      })
        .then(response => response.json())
        .then(data => {
            // here is my fetch function 
          console.log("Running setInterval() with v = " + v)
        });

    }, 2000);
    console.log("xx");
  }
}

步骤1

  • 在输入中输入一个值:“字符串1”
  • 点击输入键

输出

You pressed enter!
xx
Running setInterval() with v = string 1
Running setInterval() with v = string 1
...

步骤2

  • 在输入中输入新值:“字符串2”
  • 点击输入键

输出

...
You pressed enter!
xx
Running setInterval() with v = string 1
Running setInterval() with v = string 2
Running setInterval() with v = string 1
Running setInterval() with v = string 2
...

我的main()函数的2个实例正在运行,我想要1个实例。

如何一次运行一个函数?

1 个答案:

答案 0 :(得分:0)

您需要将间隔分配给全局变量。然后,您应该在开始新间隔之前清除旧间隔。

var odo = document.querySelector(".odometer");
var ve = document.getElementById("viewers");
var input = document.querySelector("#inputUserName");
var refreshV;

function handleEnter(e) {
  var keycode = e.keyCode ? e.keyCode : e.which;
  if (keycode == "13") {
    console.log("You pressed enter!");
    var identifiant = input.value;
    main(identifiant);
  }
}

function main(identifiant) {
  streamViewers(identifiant);

  function streamViewers(v) {
    clearInterval(refreshV);
    refreshV = setInterval(() => { response
      fetch(`https://api.twitch.tv/helix/streams?user_id=${v}`, {
          headers: {
            "client-id": "0ikjx4yg4ifvnm010hu1p5w8c4pjgm"
          }
        })
        .then(response => response.json())
        .then(data => {
          // here is my fetch function 
          console.log("Running setInterval() with v = " + v)
        });

    }, 2000);
    console.log("xx");
  }
}