如何使用 setTimeout 等待变量被加载,同时接收 HTTP 请求! [英] how to wait with setTimeout until a variable get loaded and, at the same time, receive HTTP requests!

查看:63
本文介绍了如何使用 setTimeout 等待变量被加载,同时接收 HTTP 请求!的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在 J​​avaScript 中创建了一个函数来每 100 毫秒检查一次是否加载了全局变量.当变量被加载时,函数将返回变量的值如下图所示的变量.在我的代码中,我使用 JavaScript 中的 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 以 null 启动.问题是 [2] 中的算术运算是在 myVar 获得其值之前完成的.相反,我希望我的代码等到 myVar 得到其值,然后继续操作.

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.

在尝试 setTimeout 函数之前,我尝试使用 while 循环让代码等待,但问题是由于 while 循环的不断执行,HTTP 服务器无法接收任何 HTTP 请求!

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?

先谢谢你!

推荐答案

我可能会将剩余的算术运算设为回调.类似的东西:

I would probably make the remaining arithmetric operations a callback. Something like:

function checkVariable()
{
    if ( myvar != null )
    {
            computeVariable(myVar);
    }
    else
    {
            window.setTimeout("checkVariable();",100);
    }
} 

那么:

// arithmetis operations... [1]

myVar = checkVariable();

function computeVariable(myVar) {
  // arithmetic operations that use myVar [2]
}

这篇关于如何使用 setTimeout 等待变量被加载,同时接收 HTTP 请求!的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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