虽然未定义变量 - 等待

时间:2022-11-05 19:41:05

I have a click event that is triggered from another place automatically for the first time. My problem is that it runs too soon, since the required variables are still being defined by Flash and web services. So right now I have:

我有一个点击事件,这是第一次从另一个地方自动触发。我的问题是它运行得太快,因为Flash和Web服务仍然定义了所需的变量。所以现在我有:

(function ($) {
    $(window).load(function(){
        setTimeout(function(){
            $('a.play').trigger("click");
        }, 5000);
    });
})(jQuery);

The problem is that 5 seconds for a person with a slow internet connection could be too fast and vice versa, for a person with a fast internet connection, it's too slow.

问题是,对于互联网连接速度较慢的人而言,5秒钟可能太快,反之亦然,对于互联网连接速度较快的人来说,速度太慢。

So how should I do the delay or timeout until someVariable is defined?

那么在定义someVariable之前我应该​​怎么做延迟或超时?

8 个解决方案

#1


15  

I would prefer this code:

我更喜欢这个代码:

function checkVariable() {

   if (variableLoaded == true) {
       // Here is your next action
   }
 }

 setTimeout(checkVariable, 1000);

#2


71  

The following will keep looking for someVariable until it is found. It checks every 0.25 seconds.

以下将继续寻找someVariable,直到找到它为止。它每0.25秒检查一次。

function waitForElement(){
    if(typeof someVariable !== "undefined"){
        //variable exists, do what you want
    }
    else{
        setTimeout(waitForElement, 250);
    }
}

#3


3  

Instead of using the windows load event use the ready event on the document.

而不是使用Windows加载事件使用文档上的就绪事件。

$(document).ready(function(){[...]});

This should fire when everything in the DOM is ready to go, including media content fully loaded.

当DOM中的所有内容都准备就绪时(包括完全加载的媒体内容),这应该触发。

#4


3  

Here's an example where all the logic for waiting until the variable is set gets deferred to a function which then invokes a callback that does everything else the program needs to do - if you need to load variables before doing anything else, this feels like a neat-ish way to do it, so you're separating the variable loading from everything else, while still ensuring 'everything else' is essentially a callback.

这里有一个例子,其中等待设置变量的所有逻辑都被延迟到一个函数,然后调用一个回调来执行程序需要做的其他事情 - 如果你需要在做任何其他事情之前加载变量,这感觉就像一个整洁的 - 这样做的方式,所以你将变量加载与其他所有内容分开,同时仍然确保“其他所有内容”本质上都是一个回调。

var loadUser = function(everythingElse){
    var interval = setInterval(function(){
      if(typeof CurrentUser.name !== 'undefined'){
        $scope.username = CurrentUser.name;
        clearInterval(interval);
        everythingElse();
      }
    },1);
  };

  loadUser(function(){

    //everything else

  });

#5


2  

You can use this:

你可以用这个:

var refreshIntervalId = null;
refreshIntervalId = setInterval(checkIfVariableIsSet, 1000);

var checkIfVariableIsSet = function()
{
    if(typeof someVariable !== 'undefined'){
        $('a.play').trigger("click");
        clearInterval(refreshIntervalId);
    }
};

#6


2  

Shorter way:

更短的方式:

   var queue = function (args){
      typeof variableToCheck !== "undefined"? doSomething(args) : setTimeout(function () {queue(args)}, 2000);
};

You can also pass arguments

您也可以传递参数

#7


0  

You could have Flash call the function when it's done. I'm not sure what you mean by web services. I assume you have JavaScript code calling web services via Ajax, in which case you would know when they terminate. In the worst case, you could do a looping setTimeout that would check every 100 ms or so.

完成后,您可以让Flash调用该函数。我不确定你的网络服务是什么意思。我假设您有通过Ajax调用Web服务的JavaScript代码,在这种情况下,您将知道它们何时终止。在最坏的情况下,您可以执行循环setTimeout,每隔100 ms左右检查一次。

And the check for whether or not a variable is defined can be just if (myVariable) or safer: if(typeof myVariable == "undefined")

检查变量是否定义可以只是if(myVariable)或更安全:if(typeof myVariable ==“undefined”)

#8


0  

With Ecma Script 2017 You can use async-await and while together to do that And while will not crash or lock the program even variable never be true

使用Ecma Script 2017你可以使用async-await和while一起做到这一点虽然不会崩溃或锁定程序甚至变量永远不会是真的

//First define some delay function which is called from async function
function __delay__(timer) {
    return new Promise(resolve => {
        timer = timer || 2000;
        setTimeout(function () {
            resolve();
        }, timer);
    });
};

//Then Declare Some Variable Global or In Scope
//Depends on you
let Variable = false;

//And define what ever you want with async fuction
async function some() {
    while (!Variable)
        await __delay__(1000);

    //...code here because when Variable = true this function will
};
////////////////////////////////////////////////////////////
//In Your Case
//1.Define Global Variable For Check Statement
//2.Convert function to async like below

var isContinue = false;
setTimeout(async function () {
    //STOPT THE FUNCTION UNTIL CONDITION IS CORRECT
    while (!isContinue)
        await __delay__(1000);

    //WHEN CONDITION IS CORRECT THEN TRIGGER WILL CLICKED
    $('a.play').trigger("click");
}, 1);
/////////////////////////////////////////////////////////////

Also you don't have to use setTimeout in this case just make ready function asynchronous...

此外,您不必在这种情况下使用setTimeout只是使就绪函数异步...

#1


15  

I would prefer this code:

我更喜欢这个代码:

function checkVariable() {

   if (variableLoaded == true) {
       // Here is your next action
   }
 }

 setTimeout(checkVariable, 1000);

#2


71  

The following will keep looking for someVariable until it is found. It checks every 0.25 seconds.

以下将继续寻找someVariable,直到找到它为止。它每0.25秒检查一次。

function waitForElement(){
    if(typeof someVariable !== "undefined"){
        //variable exists, do what you want
    }
    else{
        setTimeout(waitForElement, 250);
    }
}

#3


3  

Instead of using the windows load event use the ready event on the document.

而不是使用Windows加载事件使用文档上的就绪事件。

$(document).ready(function(){[...]});

This should fire when everything in the DOM is ready to go, including media content fully loaded.

当DOM中的所有内容都准备就绪时(包括完全加载的媒体内容),这应该触发。

#4


3  

Here's an example where all the logic for waiting until the variable is set gets deferred to a function which then invokes a callback that does everything else the program needs to do - if you need to load variables before doing anything else, this feels like a neat-ish way to do it, so you're separating the variable loading from everything else, while still ensuring 'everything else' is essentially a callback.

这里有一个例子,其中等待设置变量的所有逻辑都被延迟到一个函数,然后调用一个回调来执行程序需要做的其他事情 - 如果你需要在做任何其他事情之前加载变量,这感觉就像一个整洁的 - 这样做的方式,所以你将变量加载与其他所有内容分开,同时仍然确保“其他所有内容”本质上都是一个回调。

var loadUser = function(everythingElse){
    var interval = setInterval(function(){
      if(typeof CurrentUser.name !== 'undefined'){
        $scope.username = CurrentUser.name;
        clearInterval(interval);
        everythingElse();
      }
    },1);
  };

  loadUser(function(){

    //everything else

  });

#5


2  

You can use this:

你可以用这个:

var refreshIntervalId = null;
refreshIntervalId = setInterval(checkIfVariableIsSet, 1000);

var checkIfVariableIsSet = function()
{
    if(typeof someVariable !== 'undefined'){
        $('a.play').trigger("click");
        clearInterval(refreshIntervalId);
    }
};

#6


2  

Shorter way:

更短的方式:

   var queue = function (args){
      typeof variableToCheck !== "undefined"? doSomething(args) : setTimeout(function () {queue(args)}, 2000);
};

You can also pass arguments

您也可以传递参数

#7


0  

You could have Flash call the function when it's done. I'm not sure what you mean by web services. I assume you have JavaScript code calling web services via Ajax, in which case you would know when they terminate. In the worst case, you could do a looping setTimeout that would check every 100 ms or so.

完成后,您可以让Flash调用该函数。我不确定你的网络服务是什么意思。我假设您有通过Ajax调用Web服务的JavaScript代码,在这种情况下,您将知道它们何时终止。在最坏的情况下,您可以执行循环setTimeout,每隔100 ms左右检查一次。

And the check for whether or not a variable is defined can be just if (myVariable) or safer: if(typeof myVariable == "undefined")

检查变量是否定义可以只是if(myVariable)或更安全:if(typeof myVariable ==“undefined”)

#8


0  

With Ecma Script 2017 You can use async-await and while together to do that And while will not crash or lock the program even variable never be true

使用Ecma Script 2017你可以使用async-await和while一起做到这一点虽然不会崩溃或锁定程序甚至变量永远不会是真的

//First define some delay function which is called from async function
function __delay__(timer) {
    return new Promise(resolve => {
        timer = timer || 2000;
        setTimeout(function () {
            resolve();
        }, timer);
    });
};

//Then Declare Some Variable Global or In Scope
//Depends on you
let Variable = false;

//And define what ever you want with async fuction
async function some() {
    while (!Variable)
        await __delay__(1000);

    //...code here because when Variable = true this function will
};
////////////////////////////////////////////////////////////
//In Your Case
//1.Define Global Variable For Check Statement
//2.Convert function to async like below

var isContinue = false;
setTimeout(async function () {
    //STOPT THE FUNCTION UNTIL CONDITION IS CORRECT
    while (!isContinue)
        await __delay__(1000);

    //WHEN CONDITION IS CORRECT THEN TRIGGER WILL CLICKED
    $('a.play').trigger("click");
}, 1);
/////////////////////////////////////////////////////////////

Also you don't have to use setTimeout in this case just make ready function asynchronous...

此外,您不必在这种情况下使用setTimeout只是使就绪函数异步...