等待,直到满足条件或在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);
相关文章