我需要睡眠代码,直到满足某些条件或超过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();
你应该能够使用Promise.race
实现这一目标。这是一个基本的例子:
let promise1 = new Promise(resolve => {
setTimeout(resolve, 500, 'one');
});
let promise2 = new Promise(resolve => {
setTimeout(resolve, 800, 'two');
});
async function fetchAndLogResult() {
let result = await Promise.race([promise1, promise2]);
console.log(result);
}
fetchAndLogResult();
这是一个替代版本,虽然没有使用async
/ await
更简洁:
let promise1 = new Promise(resolve => {
setTimeout(resolve, 500, 'one');
});
let promise2 = new Promise(resolve => {
setTimeout(resolve, 800, 'two');
});
Promise.race([promise1, promise2]).then(result => console.log(result));
在JavaScript中没有办法等待。您既可以使用settimeout
,也可以使用while循环(请记住,在发生这种情况时脚本无法运行,然后页面可能无响应)。
使用settimeout
// this function needs to return a simple string
function something() {
conditionOk = false;
var jobWillBeDoneInNMiliseconds = Math.floor(Math.random() * 10000);
timeout = 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 )
timeWas = new Date();
wait = setInterval(function() {
if (conditionOk) {
// Communicate what you were trying to return using globals
clearInterval(wait);
}
if (new Date() - timeWas > 3000) { // Timeout
// Clear this interval
clearInterval(wait);
}
}, 30);
}
随着时间
// this function needs to return a simple string
function something() {
conditionOk = false;
var jobWillBeDoneInNMiliseconds = Math.floor(Math.random() * 10000);
timeout = 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 )
timeWas = new Date();
while ((! conditionOk) && (! (new Date() - timeWas > 3000))) { // 3000 = the delay
// Do nothing
}
if (conditionOk) {
return "returned something";
}
else {
return "returned nothing";
}
}
您可能还想看看这个问题:JavaScript sleep/wait before continuing
希望这可以帮助!
好的,因为您正在使用ajax
,您可以执行以下操作:
var eventEmitter = new EventEmitter()
eventEmitter.on('myEvent', myFunction)
$.ajax(...).then(function() {
eventEmitter.emit('myEvent', {state: true})
})
setTimeout(function() { eventEmitter.emit('myEvent', {state: false}), 3000);
function myFunction() {
//you can do your checks inside here
}
你的ajax没有使用jQuery
:
var xhr = new XMLHttpRequest();
xhr.open('GET', 'myservice/username?id=some-unique-id');
xhr.onload = function() {
if (xhr.status === 200) {
eventEmitter.emit('myEvent', {state: true})
}
else {
alert('Request failed. Returned status of ' + xhr.status);
}
};
xhr.send();