如何暂停 javascript 代码执行 2 秒

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16623852/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 05:23:33  来源:igfitidea点击:

How to pause javascript code execution for 2 seconds

javascript

提问by abdullah sheikh

I want to stop execution for 2 seconds. So is this, but now follows a code block:

我想停止执行 2 秒。也是这样,但现在遵循一个代码块:

<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. I want to stop execution for two seconds?

第一次循环执行并休眠 2 秒。我想停止执行两秒钟?

回答by Khanh TO

Javascript is single-threaded, so by nature there should not be a sleep function because sleeping will block the thread. setTimeoutis 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:

Javascript 是单线程的,所以本质上不应该有睡眠功能,因为睡眠会阻塞线程。setTimeout是一种通过将事件发布到队列以供稍后执行而不阻塞线程来解决此问题的方法。但是如果你想要一个真正的 sleep 函数,你可以这样写:

function sleep(miliseconds) {
   var currentTime = new Date().getTime();

   while (currentTime + miliseconds >= new Date().getTime()) {
   }
}

Note:The above code is NOTrecommended.

注意:推荐使用上面的代码。

回答by James McLaughlin

There's no (safe) way to pause execution. You can, however, do something like this using setTimeout:

没有(安全的)方法可以暂停执行。但是,您可以使用setTimeout 执行以下操作

function writeNext(i)
{
    document.write(i);

    if(i == 5)
        return;

    setTimeout(function()
    {
        writeNext(i + 1);

    }, 2000);
}

writeNext(1);

回答by Sachin

You can use setTimeoutto do this

你可以用setTimeout做这个

function myFunction() {
    // your code to run after the timeout
}

// stop for sometime if needed
setTimeout(myFunction, 5000);

回答by Saman Gholami

This Linkmight be helpful for you.

此链接可能对您有所帮助。

Every time I've wanted a sleep in the middle of my function, I refactored to use a setTimeout().

每次我想要在我的函数中间休眠时,我都会重构以使用 setTimeout()。

回答by sixFingers

There's no way to stop execution of your code as you would do with a procedural language. You can instead make use of setTimeout and some trickery to get a parametrized timeout:

没有办法像使用过程语言那样停止执行代码。您可以改为使用 setTimeout 和一些技巧来获得参数化超时:

for (var i = 1; i <= 5; i++) {
    var tick = function(i) {
        return function() {
            console.log(i);
        }
    };
    setTimeout(tick(i), 500 * i);
}

Demo here: http://jsfiddle.net/hW7Ch/

演示在这里:http: //jsfiddle.net/hW7Ch/