wait until condition is met or timeout is passed in javascript(等待,直到满足条件或在Java脚本中传递超时)
本文介绍了等待,直到满足条件或在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脚本中传递超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:等待,直到满足条件或在Java脚本中传递超时


基础教程推荐
猜你喜欢
- 当用户滚动离开时如何暂停 youtube 嵌入 2022-01-01
- 角度Apollo设置WatchQuery结果为可用变量 2022-01-01
- 在for循环中使用setTimeout 2022-01-01
- 我什么时候应该在导入时使用方括号 2022-01-01
- 响应更改 div 大小保持纵横比 2022-01-01
- Karma-Jasmine:如何正确监视 Modal? 2022-01-01
- 悬停时滑动输入并停留几秒钟 2022-01-01
- 有没有办法使用OpenLayers更改OpenStreetMap中某些要素 2022-09-06
- 动态更新多个选择框 2022-01-01
- 在 JS 中获取客户端时区(不是 GMT 偏移量) 2022-01-01