JavaScript 中 Java 的 Thread.sleep() 等价物是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1447407/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What's the equivalent of Java's Thread.sleep() in JavaScript?
提问by Niger
What's the equivalent of Java's Thread.sleep()
in JavaScript?
Thread.sleep()
JavaScript中 Java 的等价物是什么?
采纳答案by Daniel Pryden
The simple answer is that there is no such function.
简单的答案是没有这样的功能。
The closest thing you have is:
你最接近的是:
var millisecondsToWait = 500;
setTimeout(function() {
// Whatever you want to do after the wait
}, millisecondsToWait);
Note that you especiallydon't want to busy-wait (e.g. in a spin loop), since your browser is almost certainly executing your JavaScript in a single-threaded environment.
请注意,您尤其不想忙等待(例如在自旋循环中),因为您的浏览器几乎肯定会在单线程环境中执行您的 JavaScript。
Here are a couple of other SO questions that deal with threads in JavaScript:
以下是一些处理 JavaScript 线程的其他 SO 问题:
And this question may also be helpful:
这个问题也可能有帮助:
回答by Malaxeur
You can either write a spin loop (a loop that just loops for a long period of time performing some sort of computation to delay the function) or use:
您可以编写一个自旋循环(一个循环很长时间执行某种计算以延迟函数的循环)或使用:
setTimeout("Func1()", 3000);
This will call 'Func1()' after 3 seconds.
这将在 3 秒后调用“Func1()”。
Edit:
编辑:
Credit goes to the commenters, but you can pass anonymous functions to setTimeout.
归功于评论者,但您可以将匿名函数传递给 setTimeout。
setTimeout(function() {
//Do some stuff here
}, 3000);
This is much more efficient and does not invoke javascript's eval function.
这样效率更高,并且不会调用 javascript 的 eval 函数。
回答by Nick Craver
There's no direct equivalent, as it'd pause a webpage. However there is a setTimeout(), e.g.:
没有直接的等价物,因为它会暂停网页。但是有一个setTimeout(),例如:
function doSomething() {
thing = thing + 1;
setTimeout(doSomething, 500);
}
Closure example (thanks Daniel):
关闭示例(感谢 Daniel):
function doSomething(val) {
thing = thing + 1;
setTimeout(function() { doSomething(val) }, 500);
}
The second argument is milliseconds before firing, you can use this for time events or waiting before performing an operation.
第二个参数是触发前的毫秒数,您可以将其用于时间事件或在执行操作之前等待。
Edit:Updated based on comments for a cleaner result.
编辑:根据评论更新以获得更清晰的结果。
回答by The Machine
Or maybe you can use the setInterval function, to call a particular function, after the specified number of milliseconds. Just do a google for the setInterval prototype.I don't quite recollect it.
或者,您可以使用 setInterval 函数在指定的毫秒数后调用特定函数。只是为 setInterval 原型做一个谷歌。我不太记得了。
回答by David Miró
Try with this code. I hope it's useful for you.
尝试使用此代码。我希望它对你有用。
function sleep(seconds)
{
var e = new Date().getTime() + (seconds * 1000);
while (new Date().getTime() <= e) {}
}
回答by crazymike79
This eventually helped me:
这最终帮助了我:
var x = 0;
var buttonText = 'LOADING';
$('#startbutton').click(function(){
$(this).text(buttonText);
window.setTimeout(addDotToButton,2000);
})
function addDotToButton(){
x++;
buttonText += '.';
$('#startbutton').text(buttonText);
if (x < 4) window.setTimeout(addDotToButton, 2000);
else location.reload(true);
}
回答by Eranga
setTimeout would not hold and resume on your own thread however Thread.sleep does. There is no actual equal in Javascript
setTimeout 不会在您自己的线程上保持和恢复,但是 Thread.sleep 会。Javascript 中没有实际的相等
回答by Richrd
Assuming you're able to use ECMAScript 2017 you can emulate similar behaviour by using async/await and setTimeout. Here's an example sleep function:
假设您能够使用 ECMAScript 2017,您可以通过使用 async/await 和 setTimeout 来模拟类似的行为。下面是一个睡眠函数示例:
async function sleep(msec) {
return new Promise(resolve => setTimeout(resolve, msec));
}
You can then use the sleep function in any other async function like this:
然后,您可以在任何其他异步函数中使用 sleep 函数,如下所示:
async function testSleep() {
console.log("Waiting for 1 second...");
await sleep(1000);
console.log("Waiting done."); // Called 1 second after the first console.log
}
This is nice because it avoids needing a callback. The down side is that it can only be used in async functions. Behind the scenes the testSleep function is paused, and after the sleep completes it is resumed.
这很好,因为它避免了需要回调。缺点是它只能用于异步函数。在后台, testSleep 函数被暂停,并在睡眠完成后恢复。
From MDN:
来自 MDN:
The await expression causes async function execution to pause until a Promise is fulfilled or rejected, and to resume execution of the async function after fulfillment.
await 表达式导致异步函数执行暂停,直到 Promise 被履行或拒绝,并在履行后恢复异步函数的执行。
For a full explanation see:
完整的解释见:
回答by Toprak
For Best solution, Use async/await statement for ecma script 2017
对于最佳解决方案,请为 ecma 脚本 2017 使用 async/await 语句
await can use only inside of async function
await 只能在 async 函数内部使用
function sleep(time) {
return new Promise((resolve) => {
setTimeout(resolve, time || 1000);
});
}
await sleep(10000); //this method wait for 10 sec.
Note : async / await not actualy stoped thread like Thread.sleep but simulate it
注意:async / await 并没有像 Thread.sleep 那样实际停止线程而是模拟它