javascript - 等到满足条件或在 javascript 中传递超时

标签 javascript sleep

我需要休眠代码,直到满足某些条件或超过 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 的回答并根据我的需要对其进行了改进。我认为这回答了最初的问题。

const sleepUntil = async (f, timeoutMs) => {
    return new Promise((resolve, reject) => {
        const timeWas = new Date();
        const 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);
    });
}

用法(异步/等待 promise ):

try {
    await sleepUntil(() => document.querySelector('.my-selector'), 5000);
    // ready
} catch {
    // timeout
}

用法(.then promise ):

sleepUntil(() => document.querySelector('.my-selector'), 5000)
    .then(() => {
        // ready
    }).catch(() => {
        // timeout
    });

关于javascript - 等到满足条件或在 javascript 中传递超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49054748/

相关文章:

javascript - 将 Regex 对象分配给 html 输入模式

c - sleep() 会阻塞吗?

javascript - 您的网页何时可以休眠

javascript - 将 JSON 转换为 HTML 树

javascript - Codepen Carousel 无法正常显示或运行?

Javascript,奇怪的 float 无限小数?

javascript - 在interact.js中使用snap调整大小

python - 等待文件的脚本在 while 循环中使用 100% CPU

java - Thread.sleep(milis) 函数是否使所有线程 sleep ?

c - sleep() 以 float 作为参数不起作用