Check if function can be called: Javascript

别来无恙 提交于 2019-12-25 05:29:12

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!