Javascript is single-threaded, so by nature there should not be a sleep function because sleeping will block the thread.(Javascript是单线程的,所以本质上不应该有睡眠功能,因为睡眠会阻塞线程。)
setTimeout
is a way to get around this by posting an event to the queue to be executed later without blocking the thread.(setTimeout
是一种通过将事件发布到队列以便稍后执行而不阻塞线程来解决此问题的方法。) But if you want a true sleep function, you can write something like this:(但是如果你想要一个真正的睡眠功能,你可以这样写:)
function sleep(miliseconds) {
var currentTime = new Date().getTime();
while (currentTime + miliseconds >= new Date().getTime()) {
}
}
Note: The above code is NOT recommended.(注意: 不建议使用上述代码。)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…