我无法在 setInterval es6 中更改全局变量
I can't change global variable inside setInterval es6
我必须在按钮出现时找到它。为此,我使用 setInterval。当它找到这个按钮时,它会为我的变量提供所需的值。我在 setTimeout 中检查它,但是在 setTimeout 之后(在这些方法之外)我的全局变量变得和 setTimeout 之前一样。如何解决?
let foundValue;
function findById(id) {
let interval = setInterval(() => {
if (document.getElementById(id)){
let foundValue = document.getElementById(id);
clearInterval(interval);
}
}, 1000);
return foundValue;
}
这是因为您在 setInterval
中重新声明了 foundValue
,所以您应该删除第二个 let
,例如:
let foundValue;
function findById(id) {
let interval = setInterval(() => {
if (document.getElementById(id)){
foundValue = document.getElementById(id);
clearInterval(interval);
}
}, 1000);
return foundValue;
}
我必须在按钮出现时找到它。为此,我使用 setInterval。当它找到这个按钮时,它会为我的变量提供所需的值。我在 setTimeout 中检查它,但是在 setTimeout 之后(在这些方法之外)我的全局变量变得和 setTimeout 之前一样。如何解决?
let foundValue;
function findById(id) {
let interval = setInterval(() => {
if (document.getElementById(id)){
let foundValue = document.getElementById(id);
clearInterval(interval);
}
}, 1000);
return foundValue;
}
这是因为您在 setInterval
中重新声明了 foundValue
,所以您应该删除第二个 let
,例如:
let foundValue;
function findById(id) {
let interval = setInterval(() => {
if (document.getElementById(id)){
foundValue = document.getElementById(id);
clearInterval(interval);
}
}, 1000);
return foundValue;
}