我有一个第一次从另一个地方自动触发的click事件。我的问题是它运行得太快了,因为所需的变量仍然由Flash和web服务定义。所以现在我有:
(function ($) {
$(window).load(function(){
setTimeout(function(){
$('a.play').trigger("click");
}, 5000);
});
})(jQuery);问题是,对于一个网速很慢的人来说,5秒可能太快了,反之亦然,对于一个网速很快的人来说,这太慢了。
那么在定义someVariable之前,我应该如何处理延迟或超时呢?
发布于 2019-05-20 15:39:15
async, await实现,对@Toprak's answer的改进
(async() => {
console.log("waiting for variable");
while(!window.hasOwnProperty("myVar")) // define the condition as you like
await new Promise(resolve => setTimeout(resolve, 1000));
console.log("variable is defined");
})();
console.log("above code doesn't block main function stack");在重新考虑了行动的问题之后。实际上有一种更好的方法来实现它的意图:“变量集回调”。虽然下面的代码仅在所需变量由对象(或窗口)封装而不是由let或var声明时才有效(我留下了第一个答案,因为我只是在对现有答案进行改进,而没有实际阅读原始问题):
let obj = encapsulatedObject || window;
Object.defineProperty(obj, "myVar", {
configurable: true,
set(v){
Object.defineProperty(obj, "myVar", {
configurable: true, enumerable: true, writable: true, value: v });
console.log("window.myVar is defined");
}
});请参阅Object.defineProperty或使用es6 proxy (这可能有些夸大其词)
如果您正在寻找更多信息:
/**
* combining the two as suggested by @Emmanuel Mahuni,
* and showing an alternative to handle defineProperty setter and getter
*/
let obj = {} || window;
(async() => {
let _foo = await new Promise(res => {
Object.defineProperty(obj, "foo", { set: res });
});
console.log("obj.foo is defined with value:", _foo);
})();
/*
IMPORTANT: note that obj.foo is still undefined
the reason is out of scope of this question/answer
take a research of Object.defineProperty to see more
*/
// TEST CODE
console.log("test start");
setTimeout(async () => {
console.log("about to assign obj.foo");
obj.foo = "Hello World!";
// try uncomment the following line and compare the output
// await new Promise(res => setTimeout(res));
console.log("finished assigning obj.foo");
console.log("value of obj.foo:", obj.foo); // undefined
// console: obj.foo is defined with value: Hello World!
}, 2000);
发布于 2011-09-05 20:23:39
下面的代码将继续查找someVariable,直到找到为止。它每0.25秒检查一次。
function waitForElement(){
if(typeof someVariable !== "undefined"){
//variable exists, do what you want
}
else{
setTimeout(waitForElement, 250);
}
}发布于 2011-09-05 20:26:37
我更喜欢这样的代码:
function checkVariable() {
if (variableLoaded == true) {
// Here is your next action
}
}
setTimeout(checkVariable, 1000);https://stackoverflow.com/questions/7307983
复制相似问题