javascript - 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步
- 在输入中输入一个值:“字符串 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 个实例。
如何运行一次函数?
解决方案
您需要将间隔分配给全局变量。然后你应该在开始一个新的间隔之前清除旧的间隔。
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");
}
}
推荐阅读
- c# - 远程连接断开时如何在远程服务器中模拟鼠标单击或移动?
- javascript - Webpack:无效的配置对象/无效的模块条目
- java - 如何避免空指针异常使我的应用程序崩溃?
- javascript - 如何将事件对象传递给嵌套函数?
- javascript - ReactJS 导出到 Excel 工作表
- docker - 在 Kubernetes 集群中部署 Jenkins
- kubernetes - 版本“rbac.istio.io/v1alpha1”中的种类“ClusterRbacConfig”没有匹配项
- .net-core - .Net Core EF 核心,当我尝试添加实体时,是否存在另一个具有相同 ID 键的实例?
- android - Nativescript TypeError:无法读取未定义的属性“项目”
- php - 如何使用 PHP 中的“getopt”函数进行 CLI 参数解析?