问题
I'm trying to write a Javascript function that calls doSomething() continuously, as long as some_condition is true. If some_condition becomes false, it should check after five seconds whether some_condition has again become true, and if not, display an error message on the screen.
I currently have this much of the function written, but am confused about whether I am doing this correctly. Thanks for the help.
while (some_condition) {
doSomething();
else {
???
}
回答1:
No, you should not use a while loop. JavaScript is single threaded, and if you have a while loop that never returns, the browser (or your JavaScript environment of choice) will become unresponsive.
You need to use setTimeout to schedule the function.
function enqueueSomething() {
if (some_condition)
doSomething();
// Enqueue ourselves to run again without blocking the thread of execution
setTimeout(enqueueSomething);
else
// Wait 5 seconds, then try again
setTimeout(enqueueSomething, 5000);
}
You'll need to maintain some state that indicates whether you've previously waiting 5 seconds, and add your error-alerting code.
来源:https://stackoverflow.com/questions/31413802/check-if-function-can-be-called-javascript