如何使用 setTimeout 等待变量加载,同时接收 HTTP 请求!
我在 JavaScript 中创建了一个函数,每 100 毫秒检查一次是否加载了全局变量。 当变量被加载时,函数将返回变量的值 变量如下所示。在我的代码中,我使用 JavaScript 中的 HTTP 服务器, 当带有特定内容的特定 HTTP 请求时,将加载该变量 标头到达我的服务器。
function checkVariable()
{
if ( myvar != null )
{
return myVar;
}
else
{
window.setTimeout("checkVariable();",100);
}
}
我在如下代码中使用此函数:
// arithmetis operations... [1]
myVar = checkVariable();
// arithmetic operations that use myVar [2]
myVar 以 null 启动。问题在于 [2] 中的算术运算是在 myVar 获得其值之前完成的。相反,我希望我的代码等到 myVar 得到 其值,然后继续操作。
在尝试 setTimeout 函数之前,我尝试使用 while 循环让代码等待,但随后的问题是,由于 while 循环不断执行,HTTP 服务器无法接收任何 HTTP 请求!
有人可以帮我解决这个问题吗?
先感谢您!
I' ve made a in JavaScript function to check every 100 ms if a global variable is loaded.
When the variable will be loaded the function will return the value of the
variable as shown below. In my code I use an HTTP server in JavaScript,
and the variable will be loaded when a specific HTTP request with specific
headers arrive to my server.
function checkVariable()
{
if ( myvar != null )
{
return myVar;
}
else
{
window.setTimeout("checkVariable();",100);
}
}
I use this function in a piece of code like this:
// arithmetis operations... [1]
myVar = checkVariable();
// arithmetic operations that use myVar [2]
myVar is initiated with null. The problem is that the arithmetic operations in [2] are done before myVar got its value. Instead, I want my code to wait until myVar get
its value, and then to continue with the operations.
Before trying the setTimeout function, I tried to make the code waiting using a while loop, but the problem then was that the HTTP server couldn't receive any HTTP request due to the continuously execution of the while loop!
Could someone help me to solve this problem?
Thank you in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我可能会将剩余的算术运算作为回调。类似于:
然后:
I would probably make the remaining arithmetric operations a callback. Something like:
Then: