首页 > 解决方案 > 2 setInterval() 实例正在运行,如何运行一个?

问题描述

双打 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步

输出

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

第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 个实例。

如何运行一次函数?

标签: javascriptfunctionvariablessetinterval

解决方案


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

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");
  }
}


推荐阅读