【问题标题】:2 setInterval() instance are running, how to run one?2 setInterval() 实例正在运行,如何运行一个?
【发布时间】:2019-10-03 01:04:34
【问题描述】:

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”
  • 点击回车键

输出

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

一个函数如何运行一次?

【问题讨论】:

  • 当您输入字符串时,您的 main 函数将启动 setInterval。当您重新输入一个字符串时,您将启动另一个 setInterval 实例而不停止第一个实例。

标签: javascript function variables setinterval


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多