有没有比下面的pausecomp函数(取自此处)更好的方法来设计JavaScript中的睡眠?
function pausecomp(millis)
{
var date = new Date();
var curDate = null;
do { curDate = new Date(); }
while(curDate-date < millis);
}
这不是JavaScript中的Sleep的重复-动作之间的延迟;我希望在函数的中间有一个真正的睡眠,而不是在代码执行之前有一段延迟。
如果您真的需要等待那么多秒,那么当前接受的使用async/await和setTimeout的解决方案是完美的。然而,如果您将其用于屏幕动画,则应该真正使用requestAnimationFrame()。此函数的功能与setTimeout非常相似,但回调仅在用户可见动画时调用。这意味着,如果您在网站上运行动画,并且用户切换选项卡,动画将暂停并节省电池寿命。
这里是使用requestAnimationFrame的wait方法的实现。它接收多个帧,并在它们全部通过后解析:
常量动画等待=(帧)=>新承诺((决心)=>{让framesPassed=0;requestAnimationFrame(函数循环(){如果(++framesPassed>=帧)返回resolve();requestAnimationFrame(循环);});});//演示用打字机效果const content=document.querySelector(“.content”);异步函数类型Writer(endText,等待){content.textContent=“”;for(const letter of endText){content.textContent+=字母;wait animationWait(等待);}}typeWriter(“好的。这个简单的打字机效果是requestAnimationFrame的一个例子。”,8);<p>动画将在下面播放;尝试切换选项卡并查看动画暂停。</p><code class=“content”></code>
阅读有关requestAnimationFrame的更多信息
浏览器支持(IE10+)
我也遇到过类似的问题,必须等待控件的存在并每隔一段时间进行检查。由于JavaScript中没有真正的休眠、等待或暂停,并且Internet Explorer中不正确支持使用wait/async,因此我使用setTimeOut并注入函数以成功找到元素。以下是完整的示例代码,因此每个人都可以复制并将其用于自己的项目:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
var ElementSearchStatus = {
None: 0,
Found: 1,
NotFound: 2,
Timeout: 3
};
var maxTimeout = 5;
var timeoutMiliseconds = 1000;
function waitForElement(elementId, count, timeout, onSuccessFunction) {
++count;
var elementSearchStatus = existsElement(elementId, count, timeout);
if (elementSearchStatus == ElementSearchStatus.None) {
window.setTimeout(waitForElement, timeoutMiliseconds, elementId, count, timeout, onSuccessFunction);
}
else {
if (elementSearchStatus == ElementSearchStatus.Found) {
onSuccessFunction();
}
}
}
function existsElement(elementId, count, timeout) {
var foundElements = $("#" + elementId);
if (foundElements.length > 0 || count > timeout) {
if (foundElements.length > 0) {
console.log(elementId + " found");
return ElementSearchStatus.Found;
}
else {
console.log("Search for " + elementId + " timed out after " + count + " tries.");
return ElementSearchStatus.Timeout;
}
}
else {
console.log("waiting for " + elementId + " after " + count + " of " + timeout);
return ElementSearchStatus.None;
}
}
function main() {
waitForElement("StartButton", 0, maxTimeout, function () {
console.log("found StartButton!");
DoOtherStuff("StartButton2")
});
}
function DoOtherStuff(elementId) {
waitForElement(elementId, 0, maxTimeout, function () {
console.log("found " + elementId);
DoOtherStuff("StartButton3");
});
}
</script>
</head>
<body>
<button type="button" id="StartButton" onclick="main();">Start Test</button>
<button type="button" id="StartButton2" onclick="alert('Hey ya Start Button 2');">Show alert</button>
</body>
</html>
sleep()的JavaScript版本是什么?
这已经在当前接受的答案中得到了回答:
await new Promise(r => setTimeout(r, 1000));
两个异步函数同时运行
最好将它放在函数sleep()中,然后等待睡眠()。要使用它,需要一些上下文:
函数sleep(ms){return new Promise(r=>setTimeout(r,ms));}(异步函数slowDemo(){console.log(“启动慢演示…”);等待睡眠(2000);console.log('lowDemo:两秒后…');})();(异步函数fastDemo(){console.log('开始快速演示…');等待睡眠(500);for(设i=1;i<6;i++){console.log('上次演示:'+(i*0.5)+'秒后…');等待睡眠(500);}})();.作为控制台包装{最大高度:100%!重要;顶部:0;}
两个异步调用依次运行–一个接一个
但假设slowDemo产生的结果是fastDemo取决于。在这种情况下,在fastDemo开始之前,slowDemo必须运行到完成:
函数sleep(ms){return new Promise(r=>setTimeout(r,ms));}(异步()=>{await(异步函数slowDemo(){console.log(“启动慢演示…”);等待睡眠(2000);console.log('slowDemo:两秒后…完成!');})();(异步函数fastDemo(){console.log('开始快速演示…');等待睡眠(500);设i=-2;对于(i=1;i<5;i++){console.log('上次演示:'+(i*0.5)+'秒后…');等待睡眠(500);}console.log('fastDemo:'+(i*0.5)+'秒后。已完成!');})();})();.作为控制台包装{最大高度:100%!重要;顶部:0;}