英文:
Keep checking if a function returns true in local storage
问题
I'm trying to check if a function returns true in an if/else statement, however I want to keep checking if the function returns true and when it does to execute the code...
我试图在if/else语句中检查函数是否返回true,但我想要持续检查函数是否返回true,当它返回true时执行代码...
How would I go about this? I have tried setInterval
and setTimeout
and it won't repeat, unless I'm missing something...
我应该如何做到这一点?我尝试过setInterval
和setTimeout
,但它不会重复,除非我漏掉了什么...
I have also tried a while
loop but this is inefficient and crashes the browser...
我还尝试过使用while
循环,但这是低效的,并且会导致浏览器崩溃...
However if I use an setInterval()
how would I clear it once x returns true?
但如果我使用setInterval()
,一旦x返回true,我该如何清除它?
Here is a snippet of my code for an example.
以下是我的示例代码片段。
function x() {
if (localStorage.getItem("a") === null) {
return false;
} else {
return true;
}
}
if (!x()) {
console.log("Returned True!");
update();
} else {
console.log("False");
}
英文:
I'm trying to check if a function returns true in an if/else statement, however I want to keep checking if the function returns true and when it does to execute the code...
How would I go about this? I have tried setInterval
and setTimeout
and it won't repeat, unless I'm missing something...
I have also tried a while
loop but this is inefficient and crashes the browser...
However if I use an setInterval()
how would I clear it once x returns true?
Here is a snippet of my code for an example.
function x() {
if (localStorage.getItem("a") === null) {
return false;
} else {
return true;
}
}
if (!x()) {
console.log("Returned True!");
update();
} else {
console.log("False");
}
答案1
得分: 1
setInterval()
应该可以工作。
function x() {
return localStorage.getItem("a") !== null;
}
let interval = setInterval(() => {
if (x()) {
console.log("Returned True!");
update();
clearInterval(interval);
} else {
console.log("False");
}
}, 500);
英文:
setInterval()
should work
function x() {
return localStorage.getItem("a") !== null;
}
let interval = setInterval(() => {
if (x()) {
console.log("Returned True!");
update();
clearInterval(interval);
} else {
console.log("False");
}
}, 500);
答案2
得分: 0
function x() {
if (localStorage.getItem("a") === null) {
return false;
} else {
return true;
}
}
setInterval(x(), 1000);
setInterval(x, 1000);
第一个将在第二个清除之前运行一次。
英文:
Are you calling your function in the interval like x() or x?
function x() {
if (localStorage.getItem("a") === null) {
return false;
} else {
return true;
}
}
setInterval(x(), 1000);
setInterval(x, 1000);
The first will run once the second till you clear it
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论