有没有比下面的pausecomp函数(取自此处)更好的方法来设计JavaScript中的睡眠?
function pausecomp(millis)
{
var date = new Date();
var curDate = null;
do { curDate = new Date(); }
while(curDate-date < millis);
}
这不是JavaScript中的Sleep的重复-动作之间的延迟;我希望在函数的中间有一个真正的睡眠,而不是在代码执行之前有一段延迟。
一行使用Promise
const wait = t => new Promise(s => setTimeout(s, t, t));
带有中止信号的字体
const wait = (x: number, signal?: AbortSignal): Promise<number> => {
return new Promise((s, f) => {
const id = setTimeout(s, x, x);
signal?.addEventListener('abort', () => {
clearTimeout(id);
f('AbortError');
});
});
};
Demo
const wait=t=>new Promise(s=>setTimeout(s,t));//用途异步函数demo(){//倒计时设i=6;而(i-){等待等待(1000);控制台日志(i);}//数字0到5的总和,延迟1秒constsum=await[…Array(6).keys()].reduce(async(a,b)=>{a=等待a;等待等待(1000);常量结果=a+b;console.log(`${a}+${b}=${result}`);返回结果;},承诺.决议(0));console.log(“sum”,总和);}demo();
一种非常简单的睡眠方式,它将与运行JavaScript的任何东西兼容。。。这段代码已经过500个条目的测试,CPU和内存的使用情况在我的web浏览器上仍然不可见。
这里有一个函数,它等待节点变为可见。。。
此函数创建一个新的上下文函数(){}以避免递归。我们在这个新上下文中放置了与调用者代码相同的代码。我们使用函数Timeout在几秒钟后调用我们的函数。
var get_hyper = function(node, maxcount, only_relation) {
if (node.offsetParent === null) {
// node is hidden
setTimeout(function () { get_hyper(node, maxcount, only_relation)},
1000);
return;
};
// Enter the code here that waits for that node becoming visible
// before getting executed.
};
我同意其他海报。忙着睡觉是个坏主意。
但是,setTimeout不支持执行。它在超时设置后立即执行函数的下一行,而不是在超时过期后执行,因此无法完成睡眠所能完成的任务。
方法是将你的功能分解为前后两部分。
function doStuff()
{
// Do some things
setTimeout(continueExecution, 10000) // Wait ten seconds before continuing
}
function continueExecution()
{
// Finish doing things after the pause
}
确保你的函数名仍然准确地描述了每一块正在做的事情(即GatherInputThenWait和CheckInput,而不是funcPart1和funcPart2)
此方法实现了在超时之后才执行您决定的代码行的目的,同时仍然将控制权返回到客户端PC,以执行它排队的任何其他代码。
正如评论中指出的那样,这绝对不会在循环中工作。你可以做一些花哨的(丑陋的)黑客来让它在一个循环中工作,但总的来说,这只会导致灾难性的意大利面条代码。
如果你喜欢建议,不要失去表现。setTimeout是您的预期睡眠。然而,如果您需要一种语法,其中代码被睡眠“中间分割”,我们可以这样做:
sleep = function(tm, fn){
window.setTimeout(fn, tm);
}
然后,准备如下功能:
var fnBeforeSleep = function(){
// All code before sleep
}
var fnAfterSleep = function(){
// All code after sleep
}
然后:
fnBeforeSleep();
sleep(2000, fnAfterSleep);
// Yep! Syntactically, it is very close to:
fnBeforeSleep();
sleep(2000);
fnAfterSleep();