检查函数是否可以调用:Javascript [英] Check if function can be called: Javascript

查看:93
本文介绍了检查函数是否可以调用:Javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图编写一个不断调用doSomething()的Javascript函数,只要some_condition为真。如果some_condition变为false,则应在5秒后检查some_condition是否再次变为true,如果不是,则在屏幕上显示错误消息。

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 {
    ???
}


推荐答案

不,你不应该使用一个,而循环。 JavaScript是单线程的,如果你有一个,而循环永远不会返回,那么浏览器(或你选择的JavaScript环境)将无法响应。

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.

您需要使用 setTimeout 来安排函数。

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);
}

您需要保留一些状态,指出您以前是否在等待5秒钟,然后添加错误提示代码。

You'll need to maintain some state that indicates whether you've previously waiting 5 seconds, and add your error-alerting code.

这篇关于检查函数是否可以调用:Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆