sleep()的JavaScript版本是什么?

是否有sleep比下面的pausecomp函数(从此处获取更好的方法来设计JavaScript

function pausecomp(millis)
{
    var date = new Date();
    var curDate = null;
    do { curDate = new Date(); }
    while(curDate-date < millis);
}

这不是JavaScriptSleep的重复-动作之间的延迟 ; 我希望在函数中间真正入睡,而不是在执行一段代码之前没有延迟。

Pro十三2020/03/09 18:15:44

I can understand the purpose of a sleep function if you have to deal with synchronous execution. The setInterval and setTimeout functions create a parallel execution thread which returns the execution sequence back to the main program, which is ineffective if you have to wait for a given result. Of course one may use events and handlers, but in some cases is not what is intended.

梅猪猪2020/03/09 18:15:44

您可能需要sleep()函数而不是使用setTimeout()的一种情况是,如果您有一个响应用户单击的函数,该函数最终将最终打开一个新的弹出窗口,并且您启动了一些需要很短时间的处理在显示弹出窗口之前完成。将打开的窗口移到关闭窗口中通常意味着它会被浏览器阻止。

LEvaGreen2020/03/09 18:15:44

您无法像在JavaScript中那样进行睡眠,或者,您不应这样做。运行sleep或while循环将导致用户的浏览器挂起,直到循环完成。

使用您所引用的链接中指定的计时器。

JimAJim2020/03/09 18:15:44
function sleep(milliseconds) {
  var start = new Date().getTime();
  for (var i = 0; i < 1e7; i++) {
    if ((new Date().getTime() - start) > milliseconds){
      break;
    }
  }
}
樱古一2020/03/09 18:15:44

使用Atomics.wait更新2019

应该在Node 9.3或更高版本中工作。

我在Node.js中需要一个非常准确的计时器,因此非常有用。但是,似乎浏览器中的支持非常有限。

let ms = 10000;
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);

运行了10秒的计时器基准测试。

使用setTimeout,我得到的错误最多为7000微秒。(7毫秒)

使用Atomics,我的错误似乎保持在600微秒以下。(0.6毫秒)

Pro逆天猿2020/03/09 18:15:44

我已经搜索/搜索了很多关于javascript睡眠/等待的网页...如果您希望javascript“运行,延迟,运行”,则没有任何答案。大多数人得到的是“运行,运行(无用)。东西”,“运行”或“运行,运行+延迟运行”...。

因此,我吃了一些汉堡,然后开始思考:::这是一个可行的解决方案...但是您必须将正在运行的代码切碎... :::是的,我知道,这只是一个易于阅读的重构。还是...

// ............................................ // example1:

<html>
<body>
<div id="id1">DISPLAY</div>

<script>
//javascript sleep by "therealdealsince1982"; copyrighted 2009
//setInterval
var i = 0;

function run() {
    //pieces of codes to run
    if (i==0){document.getElementById("id1").innerHTML= "<p>code segment "+ i +" is ran</p>"; }
    if (i==1){document.getElementById("id1").innerHTML= "<p>code segment "+ i +" is ran</p>"; }
    if (i==2){document.getElementById("id1").innerHTML= "<p>code segment "+ i +" is ran</p>"; }
    if (i >2){document.getElementById("id1").innerHTML= "<p>code segment "+ i +" is ran</p>"; }
    if (i==5){document.getElementById("id1").innerHTML= "<p>all code segment finished running</p>"; clearInterval(t); } //end interval, stops run
    i++; //segment of code finished running, next...
}

run();
t=setInterval("run()",1000);

</script>
</body>
</html>

// .................................... // example2:

<html>
<body>
<div id="id1">DISPLAY</div>

<script>
//javascript sleep by "therealdealsince1982"; copyrighted 2009
//setTimeout
var i = 0;

function run() {
    //pieces of codes to run, can use switch statement
    if (i==0){document.getElementById("id1").innerHTML= "<p>code segment "+ i +" ran</p>"; sleep(1000);}
    if (i==1){document.getElementById("id1").innerHTML= "<p>code segment "+ i +" ran</p>"; sleep(2000);}
    if (i==2){document.getElementById("id1").innerHTML= "<p>code segment "+ i +" ran</p>"; sleep(3000);}
    if (i==3){document.getElementById("id1").innerHTML= "<p>code segment "+ i +" ran</p>";} //stops automatically
    i++;
}

function sleep(dur) {t=setTimeout("run()",dur);} //starts flow control again after dur

run(); //starts
</script>
</body>
</html>

// ................. example3:

<html>
<body>
<div id="id1">DISPLAY</div>

<script>
//javascript sleep by "therealdealsince1982"; copyrighted 2009
//setTimeout
var i = 0;

function flow() {
    run(i);
    i++; //code segment finished running, increment i; can put elsewhere
    sleep(1000);
    if (i==5) {clearTimeout(t);} //stops flow, must be after sleep()
}

function run(segment) {
    //pieces of codes to run, can use switch statement
    if (segment==0){document.getElementById("id1").innerHTML= "<p>code segment "+ segment +" is ran</p>"; }
    if (segment==1){document.getElementById("id1").innerHTML= "<p>code segment "+ segment +" is ran</p>"; }
    if (segment==2){document.getElementById("id1").innerHTML= "<p>code segment "+ segment +" is ran</p>"; }
    if (segment >2){document.getElementById("id1").innerHTML= "<p>code segment "+ segment +" is ran</p>"; }
}

function sleep(dur) {t=setTimeout("flow()",dur);} //starts flow control again after dur

flow(); //starts flow
</script>
</body>
</html>

// .............. example4:

<html>
<body>
<div id="id1">DISPLAY</div>

<script>
//javascript sleep by "therealdealsince1982"; copyrighted 2009
//setTimeout, switch
var i = 0;

function flow() {
    switch(i)
    {
        case 0:
            run(i);
            sleep(1000);
            break;
        case 1:
            run(i);
            sleep(2000);
            break;
        case 5:
            run(i);
            clearTimeout(t); //stops flow
            break;
        default:
            run(i);
            sleep(3000);
            break;
    }
}

function run(segment) {
    //pieces of codes to run, can use switch statement
    if (segment==0){document.getElementById("id1").innerHTML= "<p>code segment "+ segment +" is ran</p>"; }
    if (segment==1){document.getElementById("id1").innerHTML= "<p>code segment "+ segment +" is ran</p>"; }
    if (segment==2){document.getElementById("id1").innerHTML= "<p>code segment "+ segment +" is ran</p>"; }
    if (segment >2){document.getElementById("id1").innerHTML= "<p>code segment "+ segment +" is ran</p>"; }
    i++; //current segment of code finished running, next...
}

function sleep(dur) {t=setTimeout("flow()",dur);} //starts flow control again after dur

flow(); //starts flow control for first time...
</script>
</body>
</html>
小小小胖2020/03/09 18:15:44

我将setTimeOut封装在Promise中以实现与其他异步任务的代码一致性:Fiddle中的 Demo

function sleep(ms)
{
    return(new Promise(function(resolve, reject) {        
        setTimeout(function() { resolve(); }, ms);        
    }));    
}

这样使用:

sleep(2000).then(function() { 
   // Do something
});

如果您曾经使用Promises,很容易记住语法。

米亚乐2020/03/09 18:15:44

  await new Promise(resolve => setTimeout(resolve, 2000));

确保您的调用函数是异步的

经过验证且工作正常

JinJinLEY2020/03/09 18:15:44

第一:

定义要执行的函数,如下所示:

function alertWorld(){
  alert("Hello World");
}

然后使用setTimeout方法安排其执行:

setTimeout(alertWorld,1000)

注意两件事

  • 第二个参数是时间(以毫秒为单位)
  • 作为第一个参数,您只需要传递函数的名称(引用),而不带括号
Sam神乐番长2020/03/09 18:15:44

我个人很简单:

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

然后:

sleep(2); // Sleeps for 2 seconds

我一直在使用它来在P5js中创建脚本时创建假加载时间

LEY小卤蛋2020/03/09 18:15:44

干得好。如代码所示,不要做坏开发者,并在网站上使用它。这是一个开发实用程序功能。

// Basic sleep function based on ms.
// DO NOT USE ON PUBLIC FACING WEBSITES.
function sleep(ms) {
    var unixtime_ms = new Date().getTime();
    while(new Date().getTime() < unixtime_ms + ms) {}
}
神乐阿飞2020/03/09 18:15:44

我也搜索了睡眠解决方案(不是用于生产代码,仅用于开发/测试),并找到了这篇文章:

http://narayanraman.blogspot.com/2005/12/javascript-sleep-or-wait.html

...这是客户端解决方案的另一个链接:http : //www.devcheater.com/

另外,在调用时alert(),代码也会被暂停,同时显示警报-需要找到一种不显示警报但获得相同效果的方法。:)

凯斯丁2020/03/09 18:15:44

我知道这是一个古老的问题,但是如果(像我一样)您在Rhino中使用Javascript,则可以使用...

try
{
  java.lang.Thread.sleep(timeInMilliseconds);
}
catch (e)
{
  /*
   * This will happen if the sleep is woken up - you might want to check
   * if enough time has passed and sleep again if not - depending on how
   * important the sleep time is to you.
   */
}
凯Harry2020/03/09 18:15:44

仅用于debug / dev,如果对某人有用,我将其发布

有趣的是,在Firebug(可能还有其他js控制台)中,仅在指定的睡眠持续时间之后,按Enter后什么也没有发生(...)

function sleepFor( sleepDuration ){
    var now = new Date().getTime();
    while(new Date().getTime() < now + sleepDuration){ /* do nothing */ } 
}

使用示例:

function sleepThenAct(){ sleepFor(2000); console.log("hello js sleep !"); }
小卤蛋小卤蛋小哥2020/03/09 18:15:44

我同意其他海报,繁忙的睡眠只是一个坏主意。

However, setTimeout does not hold up execution, it executes the next line of the function immediately after the timeout is SET, not after the timeout expires, so that does not accomplish the same task that a sleep would accomplish.

The way to do it is to breakdown your function in to before and after parts.

function doStuff()
{
  //do some things
  setTimeout(continueExecution, 10000) //wait ten seconds before continuing
}

function continueExecution()
{
   //finish doing things after the pause
}

Make sure your function names still accurately describe what each piece is doing (I.E. GatherInputThenWait and CheckInput, rather than funcPart1 and funcPart2)

Edit

This method achieves the purpose of not executing the lines of code you decide until AFTER your timeout, while still returning control back to the client PC to execute whatever else it has queued up.

Further Edit

As pointed out in the comments this will absolutely NOT WORK in a loop. You could do some fancy (ugly) hacking to make it work in a loop, but in general that will just make for disastrous spaghetti code.

Mandy小胖Pro2020/03/09 18:15:44

(请参阅2016年更新的答案

我认为执行一个动作,等待,然后执行另一个动作是完全合理的。如果您习惯于使用多线程语言编写代码,那么您可能会想到在一段特定的时间内让执行程序唤醒您的线程。

这里的问题是JavaScript是基于事件的单线程模型。虽然在特定情况下,让整个引擎等待几秒钟可能会很好,但是通常这是一种不好的做法。假设我想在编写自己的函数时使用您的函数?当我调用您的方法时,我的方法将全部冻结。如果JavaScript可以某种方式保留函数的执行上下文,将其存储在某个地方,然后将其带回并稍后继续,则可能会发生睡眠,但这基本上就是线程化。

因此,您几乎会被别人的建议所束缚-您需要将代码分解为多个功能。

那么,您的问题是一个错误的选择。您无法以自己想要的方式入睡,也不应追求您建议的解决方案。