Javascript 如何使用 setTimeout 等待变量被加载,同时接收 HTTP 请求!

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3224097/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:45:09  来源:igfitidea点击:

how to wait with setTimeout until a variable get loaded and, at the same time, receive HTTP requests!

javascriptsettimeout

提问by Thanasis Petsas

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.

我已经在 J​​avaScript 中创建了一个函数来每 100 毫秒检查一次是否加载了全局变量。加载变量时,函数将返回变量的值,如下所示。在我的代码中,我使用 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. 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.

myVar 以 null 启动。问题是 [2] 中的算术运算是在 myVar 获得其值之前完成的。相反,我希望我的代码等到 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 循环使代码等待,但问题是由于持续执行 while 循环,HTTP 服务器无法接收任何 HTTP 请求!

Could someone help me to solve this problem?

有人可以帮我解决这个问题吗?

Thank you in advance!

先感谢您!

回答by jpoz

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]
}