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");
}
}
输出
You pressed enter!
xx
Running setInterval() with v = string 1
Running setInterval() with v = string 1
...
输出
...
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个实例。
答案 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");
}
}