等待,直到满足条件或在Java脚本中传递超时 [英] wait until condition is met or timeout is passed in javascript

查看:29
本文介绍了等待,直到满足条件或在Java脚本中传递超时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要让代码休眠,直到满足某个条件或超过3秒超时。然后返回一个简单的字符串。有什么办法可以让我这样做吗?

// this function needs to return a simple string 

function something() { 

    var conditionOk = false;

    var jobWillBeDoneInNMiliseconds = Math.floor(Math.random() * 10000);

    setTimeout(function() {

        // I need to do something here, but I don't know how long it takes
        conditionOk = true; 

    }, jobWillBeDoneInNMiliseconds);


    // I need to stop right here until
    // stop here until ( 3000 timeout is passed ) or ( conditionOk == true )
    StopHereUntil( conditionOk, 3000 );

    return "returned something"; 
}

以下是我要做的事情:

我让浏览器滚动到页面底部,然后调用一些AJAX函数来获取评论(我无法控制它)。现在我需要等待注释出现在包含".Comment"类的文档中。

我需要getComments()函数以json字符串形式返回注释。

function getComments() {

    window.scrollTo(0, document.body.scrollHeight || document.documentElement.scrollHeight);

  var a = (document.querySelectorAll('div.comment'))

  // wait here until  (  a.length > 0  ) or ( 3 second is passed )

  // then I need to collect comments
  var comments = [];
  document.querySelectorAll('div.comment p')
    .forEach(function(el){      
        comments.push(el.text());
    });

  return JSON.stringify(comments);
} 

getComments();

推荐答案

我遇到了这个问题,没有一个解决方案令人满意。我需要等到某个元素出现在DOM中。因此,我采纳了Hedgehog125的答案,并对其进行了改进,以满足我的需求。我认为这回答了最初的问题。

async function sleepUntil(f, timeoutMs) {
    return new Promise((resolve, reject) => {
        let timeWas = new Date();
        let wait = setInterval(function() {
            if (f()) {
                console.log("resolved after", new Date() - timeWas, "ms");
                clearInterval(wait);
                resolve();
            } else if (new Date() - timeWas > timeoutMs) { // Timeout
                console.log("rejected after", new Date() - timeWas, "ms");
                clearInterval(wait);
                reject();
            }
        }, 20);
    });
}

用法:

await sleepUntil(() => document.querySelector('.my-selector'), 5000);

这篇关于等待,直到满足条件或在Java脚本中传递超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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