Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
473 views
in Technique[技术] by (71.8m points)

javascript - 如何暂停javascript代码执行2秒[重复](How to pause javascript code execution for 2 seconds [duplicate])

This question already has an answer here:(这个问题在这里已有答案:)

I want to stop execution for 2 seconds.(我想停止执行2秒钟。)

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>

For the first time loop is excute and sleep for 2 seconds.(第一次循环是执行并睡眠2秒。)

I want to stop execution for two seconds?(我想停止执行两秒钟?)   ask by abdullah sheikh translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.(注意: 建议使用上述代码。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...