JavaScript中与java的Thread.sleep()等价的是什么?

JavaScript中与Java的Thread.sleep()等价的是什么?

255041 次浏览

你可以写一个自旋循环(一个循环,只是循环很长一段时间执行某种计算来延迟函数)或使用:

setTimeout("Func1()", 3000);

这将在3秒后调用'Func1()'。

编辑:

信用归评论者,但您可以将匿名函数传递给setTimeout。

setTimeout(function() {
//Do some stuff here
}, 3000);

这样效率更高,而且不需要调用javascript的eval函数。

没有直接的对等物,因为它会暂停一个网页。然而,有一个setTimeout (),例如:

function doSomething() {
thing = thing + 1;
setTimeout(doSomething, 500);
}

闭包例子(谢谢Daniel):

function doSomething(val) {
thing = thing + 1;
setTimeout(function() { doSomething(val) }, 500);
}

第二个参数是触发前的毫秒数,您可以将其用于时间事件或执行操作前的等待。

编辑:根据注释更新,以获得更清晰的结果。

简单的答案是不存在这样的函数。

最接近你的东西是:

var millisecondsToWait = 500;
setTimeout(function() {
// Whatever you want to do after the wait
}, millisecondsToWait);

注意,你特别是不希望忙碌等待(例如在一个旋转循环中),因为你的浏览器几乎肯定是在单线程环境中执行你的JavaScript。

下面是一些其他关于JavaScript线程的SO问题:

这个问题可能也有帮助:

或者您可以使用setInterval函数,在指定的毫秒数之后调用特定的函数。只需为setInterval原型执行谷歌即可。我不太记得了。

试试这段代码。我希望这对你有用。

function sleep(seconds)
{
var e = new Date().getTime() + (seconds * 1000);
while (new Date().getTime() <= e) {}
}

这最终帮助了我:

    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);
}

setTimeout不会在你自己的线程上保持和恢复。睡眠。在Javascript中没有真正的对等

假设你能够使用ECMAScript 2017,你可以通过使用async/await和setTimeout来模拟类似的行为。下面是一个睡眠函数的例子:

async function sleep(msec) {
return new Promise(resolve => setTimeout(resolve, msec));
}

然后你可以在任何其他异步函数中使用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
}

这很好,因为它避免了需要回调。缺点是它只能在异步函数中使用。在后台,testSleep函数被暂停,在睡眠完成后,它将被恢复。

中数:

await表达式导致async函数的执行暂停,直到a Promise被满足或拒绝,并恢复异步的执行

完整的解释见:

为获得最佳解决方案,ecma脚本2017使用async/await语句

Await只能在async函数内部使用

function sleep(time) {
return new Promise((resolve) => {
setTimeout(resolve, time || 1000);
});
}


await sleep(10000); //this method wait for 10 sec.

注意:async / await不像thread那样实际停止线程。睡眠但模拟它