如何暂停javascript代码执行2秒钟 [英] How to pause javascript code execution for 2 seconds
本文介绍了如何暂停javascript代码执行2秒钟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想停止执行2秒钟。这是这样,但现在遵循一个代码块:
I want to stop execution for 2 seconds. So is this, but now follows a code block:
<html>
<head>
<title> HW 10.12 </title>
<script type="text/javascript">
for (var i = 1; i <= 5; i++) {
document.write(i);
sleep(2); //for the first time loop is excute and sleep for 2 seconds
};
</script>
</head>
<body></body>
</html>
第一次循环是执行并且睡眠2秒。我想停止执行两秒钟?
For the first time loop is excute and sleep for 2 seconds. I want to stop execution for two seconds?
推荐答案
Javascript是单线程的,所以本质上不应该有睡眠功能因为睡觉会阻塞线程。 setTimeout
是一种通过将事件发布到队列以便稍后执行而不阻塞线程来解决此问题的方法。但是如果你想要一个真正的睡眠功能,你可以这样写:
Javascript is single-threaded, so by nature there should not be a sleep function because sleeping will block the thread. setTimeout
is a way to get around this by posting an event to the queue to be executed later without blocking the thread. 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()) {
}
}
注意:以上代码建议不。
这篇关于如何暂停javascript代码执行2秒钟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文