[英]how to wait with setTimeout until a variable get loaded and, at the same time, receive HTTP requests!
I' ve made a in JavaScript function to check every 100 ms if a global variable is loaded. 如果加载了全局变量,我已经在JavaScript函数中检查每100毫秒。 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.
在我的代码中,我在JavaScript中使用HTTP服务器,当具有特定标头的特定HTTP请求到达我的服务器时,将加载该变量。
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. myVar以null启动。 The problem is that the arithmetic operations in [2] are done before myVar got its value.
问题是[2]中的算术运算是在myVar得到它的值之前完成的。 Instead, I want my code to wait until myVar get its value, and then to continue with the operations.
相反,我希望我的代码等到myVar得到它的值,然后继续操作。
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! 在尝试setTimeout函数之前,我尝试使用while循环使代码等待,但问题是HTTP服务器由于连续执行while循环而无法接收任何HTTP请求!
Could someone help me to solve this problem? 有人可以帮我解决这个问题吗?
Thank you in advance! 先感谢您!
I would probably make the remaining arithmetric operations a callback. 我可能会将剩余的算术运算作为回调。 Something like:
就像是:
function checkVariable()
{
if ( myvar != null )
{
computeVariable(myVar);
}
else
{
window.setTimeout("checkVariable();",100);
}
}
Then: 然后:
// arithmetis operations... [1]
myVar = checkVariable();
function computeVariable(myVar) {
// arithmetic operations that use myVar [2]
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.