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

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

问题是,对于一个网速很慢的人来说,5秒可能太快了,反之亦然,对于一个网速很快的人来说,这太慢了.

那么,在定义someVariable之前,我应该如何进行延迟或超时呢?

推荐答案

async, await implementation, improvement over @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");

After revisiting the OP's question. There is actually a better way to implement what was intended: "variable set callback". Although the below code only works if the desired variable is encapsulated by an object (or window) instead of declared by let or var (I left the first answer because I was just doing improvement over existing answers without actually reading the original question):

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);

Jquery相关问答推荐

通过 Ajax POST 将按钮值从 HTML 发送到 Flask 时出现空数据

使用 JQuery 在 span 标签中用逗号分隔页面上的文本

如何判断是否有任何 JavaScript 事件侦听器/处理程序附加到元素/文档?

用jquery查找div底部的位置

Bootstrap 3.0 弹出框和工具提示

为什么 Chrome 会忽略本地 jQuery cookie?

从父 node 中删除所有子 node ?

复选框值始终为打开

用jquery替换锚文本

您如何处理 jQuery 中的表单更改?

jQuery 日期 Select 器 - 禁用过go 的日期

用作 Google Chrome 书签

检测夹点的最简单方法

如何测试 URL 字符串是绝对的还是相对的?

jQuery $(".class").click(); - 多个元素,点击事件一次

如何防止使用光标拖动 Select 文本/元素

将数据发布到 JsonP

检测页面是否已完成加载

如何插入元素作为第一个子元素?

jQuery 使用 AND 和 OR 运算符按属性 Select