什么是sleep()的JavaScript版本?

有没有更好的方法来devise一个sleep JavaScript比下面的pausecomp函数( 从这里取得 )?

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

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

2017更新

自2009年问这个问题以来,JavaScript已经发生了很大的变化。 所有其他答案现在已经过时或过于复杂。 这是目前的最佳做法:

 function sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } async function demo() { console.log('Taking a break...'); await sleep(2000); console.log('Two second later'); } demo(); 

就是这个。 await sleep(<duration>)

你可以在Runkit上试试这段代码。 注意,

  1. await只能在以async关键字为前缀的函数中执行。 运行包在执行之前将代码封装在asynchronous函数中。
  2. await暂停当前​​的asyncfunction

两个新的JavaScriptfunction帮助编写了这个实际的“睡眠”function:

  • 诺言,ES2015 (又名ES6) 的本地特色 。 我们也在睡眠函数的定义中使用箭头函数。
  • 即将到来的 async/awaitfunction可以让代码明确地等待承诺解决。

兼容性

  • 诺基亚在Node v0.12 +中 支持 ,除IE外, 在浏览器中得到广泛的支持
  • async / await登陆V8,并已自Chrome 55默认启用
    • 它在2016年10月降落在节点7
    • 也于2016年11月至11月间在Firefox登陆

如果由于某种原因,您使用的节点年龄超过7岁,或者是针对老的浏览器, async / await仍然可以通过Babel (一种将JavaScript +新function转换成普通的旧JavaScript的工具)来使用, transform-async-to-generator插件 。 跑

 npm install babel-cli --save 

创build.babelrc与:

 { "plugins": [ "transform-async-to-generator", ] } 

然后运行你的代码

 node_modules/babel-cli/bin/babel-node.js sleep.js 

但是,如果您使用的是Node 7或更高版本,或者您的目标是新式浏览器,则不需要这些。

(请参阅2016年更新的答案 )

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

这里的问题是JavaScript是一个基于事件的单线程模型。 在特定情况下,整个引擎等待几秒钟可能会很好,但总的来说这是不好的做法。 假设我想在写我自己的时候使用你的function? 当我调用你的方法时,我的方法都会冻结。 如果JavaScript可以以某种方式保存你的函数的执行上下文,将它存储在某个地方,然后把它放回来,然后继续,然后睡觉可能发生,但基本上是线程化。

所以你几乎坚持别人的build议 – 你需要把你的代码分解成多个函数。

那么你的问题就是一个错误的select。 没有办法以你想要的方式睡觉,也不应该追求你所build议的解决scheme。

在JavaScript中,我重写了每个函数,以便它可以尽快结束。 你想让浏览器重新控制,这样可以改变你的DOM。

每次我在我的函数中想要一个睡眠,我重构使用setTimeout()

我要编辑这个答案,因为我发现这是有用的:

臭名昭着的睡眠或延迟function在任何语言中都有很多争议。 有人会说,应该总是有一个信号或callback来触发一个给定的function,其他人会争辩说,有时任意时刻的延迟是有用的。 我认为,对于每个人来说,一个规则决不能决定这个行业的任何东西。

编写睡眠函数非常简单,使用JavaScript Promise更加实用:

 // sleep time expects milliseconds function sleep (time) { return new Promise((resolve) => setTimeout(resolve, time)); } // Usage! sleep(500).then(() => { // Do something after the sleep! }); 

只有debugging/开发 ,我张贴这个,如果有用的人

有趣的东西,在Firebug(&可能其他JS控制台),没有什么事后打回车,只有在指定的睡眠时间(…)

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

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

但是,setTimeout不会执行,它会在超时设置后立即执行函数的下一行,而不是在超时过期之后执行,这样就不能完成与睡眠相同的任务。

做到这一点的方法是把你的function分解成前后部分。

 function doStuff() { //do some things setTimeout(continueExecution, 10000) //wait ten seconds before continuing } function continueExecution() { //finish doing things after the pause } 

确保您的函数名称仍然准确地描述每件作品(IE GatherInputThenWait和CheckInput,而不是funcPart1和funcPart2)

编辑

这种方法达到了不执行你所决定的代码行的目的,直到超时之后,同时仍然返回到客户端PC执行任何其他排队的代码。

进一步编辑

正如在评论中指出,这绝对不会在一个循环中工作。 你可以做一些花哨的(丑陋的)黑客工作,但一般来说,这只会造成意大利面条代码。

对于$ DEITY的爱,请不要忙碌的等待睡眠function。 setTimeoutsetInterval完成你所需要的一切。

我知道这是一个古老的问题,但如果(像我一样)使用Javascript与Rhino,你可以使用…

 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. */ } 

如果你正在使用jQuery,有人实际上创build了一个“延迟”插件,这只不过是一个setTimeout的包装:

 // Delay Plugin for jQuery // - http://www.evanbot.com // - © 2008 Evan Byrne jQuery.fn.delay = function(time,func){ this.each(function(){ setTimeout(func,time); }); return this; }; 

然后,您可以按照预期在一行函数调用中使用它:

 $('#warning') .addClass('highlight') .delay(1000) .removeClass('highlight'); 

我也search睡眠解决scheme(不生产代码,只为开发/testing),并发现这篇文章:

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

…以下是与客户端解决scheme的另一个链接: http : //www.devcheater.com/

另外,当你调用alert() ,你的代码也会被暂停,当显示alert时,需要find一个不显示alert的方法,但是得到相同的效果。 🙂

干得好。 正如代码所说,不要成为一个糟糕的开发者,并在网站上使用它。 这是一个开发实用程序function。

 // 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) {} } 

下面是使用同步XMLHttpRequest的简单解决scheme:

 function sleep(n){ var request = new XMLHttpRequest(); request.open('GET', '/sleep.php?n=' + n, false); // `false` makes the request synchronous request.send(null); } 

sleep.php的内容:

 <?php sleep($_GET['n']); 

现在叫它:sleep(5);

第一:

定义一个你想要执行的函数

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

然后使用setTimeout方法计划执行:

 setTimeout(alertWorld,1000) 

注意两件事

  • 第二个参数是以毫秒为单位的时间
  • 作为第一个参数,您只需传递函数的名称(引用),而不用括号

使事情看起来像大多数人想要的更好的解决scheme是使用匿名函数:

 alert('start'); var a = 'foo'; //lots of code setTimeout(function(){ //Beginning of code that should run AFTER the timeout alert(a); //lots more code },5000); // put the timeout here 

这可能是最接近你的东西,只是做你想要的东西。

请注意,如果您需要多次睡眠,可能会变得很匆忙,您可能实际上需要重新考虑您的devise。

我个人喜欢简单:

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

然后:

 sleep(2); // Sleeps for 2 seconds 

我一直使用它来创build伪装载时间,而在P5js中创build脚本

我已经search/search了很多关于JavaScript睡眠/等待的网页…如果你想javascript运行,延迟,运行…没有答案…大多数人得到的是“RUN,RUN(无用东西),运行“或”运行,运行+延迟运行“….

所以我吃了一些汉堡,并思考:::这里是一个解决scheme的工作…但你必须切断你的运行代码… :::是的,我知道,这只是一个更容易阅读重构..还是…

// ………………………………….. // 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> 

对于浏览器,我同意setTimeout和setInterval是要走的路。

但是对于服务器端代码,可能需要一个阻塞函数(例如,所以你可以有效地进行线程同步)。

如果你使用的是node.js和meteor,你可能会遇到在光纤中使用setTimeout的限制。 这里是服务器端睡眠的代码。

 var Fiber = require('fibers'); function sleep(ms) { var fiber = Fiber.current; setTimeout(function() { fiber.run(); }, ms); Fiber.yield(); } Fiber(function() { console.log('wait... ' + new Date); sleep(1000); console.log('ok... ' + new Date); }).run(); console.log('back in main'); 

请参阅: https : //github.com/laverdet/node-fibers#sleep

这里的大多数答案都是错误的,至less是过时的。 没有理由JavaScript必须是单线程的,事实上并非如此。 今天,所有的主stream浏览器都支持工作,在此之前,像Rhino和Node.js这样的其他javascript运行时支持multithreading。

“Javascript是单线程”不是一个有效的答案。 例如,在worker中运行sleep函数不会阻塞在ui线程中运行的任何代码。

在支持生成器和良率的较新运行时,可以在单线程环境中为睡眠函数带来类似的function:

 // This is based on the latest ES6 drafts. // js 1.7+ (SpiderMonkey/Firefox 2+) syntax is slightly different // run code you want to sleep here (ommit star if using js 1.7) function* main(){ for (var i = 0; i < 10; i++) { // to sleep for 10 milliseconds 10 times in a row yield 10; } yield 5; console.log('I just slept 5 milliseconds!'); } // resume the given generator after ms milliseconds function resume(ms, generator){ setTimeout(function(){ // ommit .value if using js 1.7 var nextSleep = generator.next().value; resume(nextSleep, generator); }, ms); } // initialize generator and get first sleep for recursive function var generator = main(), firstSleep = generator.next().value; // initialize recursive resume function resume(firstSleep, generator); 

这种模拟睡眠不同于真正的睡眠function,因为它不会阻塞线程。 它只是在javascript的当前setTimeout函数之上的糖。 这个functiontypes已经在Task.js中实现,并且现在可以在Firefox中使用。

 function sleep(milliseconds) { var start = new Date().getTime(); for (var i = 0; i < 1e7; i++) { if ((new Date().getTime() - start) > milliseconds){ break; } } } 

我将setTimeOut封装在与其他asynchronous任务的代码一致性Promise中:Demo in Fiddle

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

这样使用:

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

如果您使用Promise,则很容易记住语法。

如果你必须处理同步执行,我可以理解睡眠函数的目的。 setInterval和setTimeout函数创build一个并行执行线程,它将执行序列返回到主程序,如果您必须等待给定的结果,这是无效的。 当然可以使用事件和处理程序,但在某些情况下不是打算的。

它可以使用Java的睡眠方法完成。 我已经在FF和IE中testing过了,它不locking计算机,咀嚼资源,或者造成无休止的服务器命中。 对我来说似乎是一个干净的解决scheme。

首先,您必须将Java加载到页面上并使其方法可用。 要做到这一点,我做到了这一点:

 <html> <head> <script type="text/javascript"> function load() { var appletRef = document.getElementById("app"); window.java = appletRef.Packages.java; } // endfunction </script> <body onLoad="load()"> <embed id="app" code="java.applet.Applet" type="application/x-java-applet" MAYSCRIPT="true" width="0" height="0" /> 

那么,当你想在你的JS中无痛的停顿时,你所要做的就是:

 java.lang.Thread.sleep(xxx) 

其中xxx是以毫秒为单位的时间。 在我的情况下(通过理由),这是一个非常小的公司后端订单履行的一部分,我需要打印一个发票,必须从服务器加载。 我通过将发票(作为网页)加载到iFrame中,然后打印iFrame来完成。 当然,我必须等到页面完全加载才能打印,所以JS不得不暂停。 我通过让发票页面(在iFrame中)使用onLoad事件改变父页面上的隐藏表单域来实现这一点。 然后在父页面上打印发票的代码看起来像这样(为了清楚起见剪切了不相关的部分):

 var isReady = eval('document.batchForm.ready'); isReady.value=0; frames['rpc_frame'].location.href=url; while (isReady.value==0) { java.lang.Thread.sleep(250); } // endwhile window.frames['rpc_frame'].focus(); window.frames['rpc_frame'].print(); 

因此,用户按下button,脚本加载发票页面,然后等待,每隔四分钟检查一次发票页面是否已完成加载,然后popup打印对话框以供用户将其发送到打印机。 QED。

You can't do a sleep like that in JavaScript, or, rather, you shouldn't. Running a sleep or a while loop will cause the user's browser to hang until the loop is done.

Use a timer, as specified in the link you referenced.

One scenario where you might want a sleep() function rather than using setTimeout() is if you have a function responding to a user click that will ultimately end up opening a new ie popup window and you have initiated some processing that requires a short period to complete before the popup is displayed. Moving the open window into a closure means that it typically gets blocked by the browser.

A lot of the answers don't (directly) answer the question, and neither does this one…

Here's my two cents (or functions):

If you want less clunky functions than setTimeout and setInterval , you can wrap them in functions that just reverse the order of the arguments and give them nice names:

 function after(ms, fn){ setTimeout(fn, ms); } function every(ms, fn){ setInterval(fn, ms); } 

CoffeeScript versions:

 after = (ms, fn)-> setTimeout fn, ms every = (ms, fn)-> setInterval fn, ms 

You can then use them nicely with anonymous functions:

 after(1000, function(){ console.log("it's been a second"); after(1000, function(){ console.log("it's been another second"); }); }); 

Now it reads easily as "after N milliseconds, …" (or "every N milliseconds, …")

For the specific case of wanting to space out a set of calls being executed by a loop, you can use something like the code below with prototype. Without prototype, you can substitute the delay function with setTimeout.

 function itemHandler(item) { alert(item); } var itemSet = ['a','b','c']; // Each call to itemHandler will execute // 1 second apart for(var i=0; i<itemSet.length; i++) { var secondsUntilExecution = i; itemHandler.delay(secondsUntilExecution, item) } 

Adding my two bits. I needed a busy-wait for testing purposes. I didn't want to split the code as that would be a lot of work, so a simple for did it for me.

 for (var i=0;i<1000000;i++){ //waiting } 

I don't see any downside in doing this and it did the trick for me.

If you're on node.js, you can have a look at fibers – a native C extension to node, a kinda-multi-threading simulation.

It allows you to do a real sleep in a way which is blocking execution in a fiber, but it's non-blocking in the main thread and other fibers.

Here's an example fresh from their own readme:

 // sleep.js var Fiber = require('fibers'); function sleep(ms) { var fiber = Fiber.current; setTimeout(function() { fiber.run(); }, ms); Fiber.yield(); } Fiber(function() { console.log('wait... ' + new Date); sleep(1000); console.log('ok... ' + new Date); }).run(); console.log('back in main'); 

– and the results are:

 $ node sleep.js wait... Fri Jan 21 2011 22:42:04 GMT+0900 (JST) back in main ok... Fri Jan 21 2011 22:42:05 GMT+0900 (JST) 

An old question from 2009. Now in 2015 a new solution is possible with generators defined in ECMAscript 2015 aka ES6. It was approved in June, but it was implemented in Firefox and Chrome before. Now a sleep function can be made non-busy, non-blocking and nested inside loops and sub-functions without freezing the browser. Only pure JavaScript is needed, no libraries or frameworks.

The program below shows how sleep() and runSleepyTask() can be made. The sleep() function is only a yield statement. It is so simple that it is actually easier to write the yield statement directly in stead of calling sleep() , but then there would be no sleep-word 🙂 The yield returns a time value to the next() method inside wakeup() and waits. The actual "sleeping" is done in wakeup() using the good old setTimeout() . At callback the the next() method triggers the yield statement to continue, and the "magic" of yield is that all the local variables and the whole call-stack around it is still intact.

Functions that use sleep() or yield must be defined as generators. Easy done by adding an asterix to the keyword function* . To execute a generator is a bit trickier. When invoked with the keyword new the generator returns an object that has the next() method, but the body of the generator is not executed (the keyword new is optional and makes no difference). The next() method triggers execution of the generator body until it encounters a yield . The wrapper function runSleepyTask() starts up the ping-pong: next() waits for a yield , and yield waits a next() .

Another way to invoke a generator is with keyword yield* , here it works like a simple function call, but it also includes the ability to yield back to next() .

This is all demonstrated by the example drawTree() . It draws a tree with leaves on a rotating 3D scene. A tree is drawn as a trunk with 3 parts at the top in different directions. Each part is then drawn as another but smaller tree by calling drawTree() recursively after a short sleep. A very small tree is drawn as only a leaf.

Each leaf has its own life in a separate task started with runSleepyTask() . It is born, grows, sits, fades, falls and dies in growLeaf() . The speed is controlled with sleep() . This demonstrates how easy multitasking can be done.

 function* sleep(milliseconds) {yield milliseconds}; function runSleepyTask(task) { (function wakeup() { var result = task.next(); if (!result.done) setTimeout(wakeup, result.value); })() } //////////////// written by Ole Middelboe ///////////////////////////// pen3D =setup3D(); var taskObject = new drawTree(pen3D.center, 5); runSleepyTask(taskObject); function* drawTree(root3D, size) { if (size < 2) runSleepyTask(new growLeaf(root3D)) else { pen3D.drawTrunk(root3D, size); for (var p of [1, 3, 5]) { var part3D = new pen3D.Thing; root3D.add(part3D); part3D.move(size).turn(p).tilt(1-p/20); yield* sleep(50); yield* drawTree(part3D, (0.7+p/40)*size); } } } function* growLeaf(stem3D) { var leaf3D = pen3D.drawLeaf(stem3D); for (var s=0;s++<15;) {yield* sleep(100); leaf3D.scale.multiplyScalar(1.1)} yield* sleep( 1000 + 9000*Math.random() ); for (var c=0;c++<30;) {yield* sleep(200); leaf3D.skin.color.setRGB(c/30, 1-c/40, 0)} for (var m=0;m++<90;) {yield* sleep( 50); leaf3D.turn(0.4).tilt(0.3).move(2)} leaf3D.visible = false; } /////////////////////////////////////////////////////////////////////// function setup3D() { var scene, camera, renderer, diretionalLight, pen3D; scene = new THREE.Scene(); camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000); camera.position.set(0, 15, 20); renderer = new THREE.WebGLRenderer({ alpha: true, antialias: true }); renderer.setSize(window.innerWidth, window.innerHeight); document.body.appendChild(renderer.domElement); directionalLight = new THREE.DirectionalLight(0xffffaa, 0.7); directionalLight.position.set(-1, 2, 1); scene.add(directionalLight); scene.add(new THREE.AmbientLight(0x9999ff)); (function render() { requestAnimationFrame(render); // renderer.setSize( window.innerWidth, window.innerHeight ); scene.rotateY(10/60/60); renderer.render(scene, camera); })(); window.addEventListener( 'resize', function(){ renderer.setSize( window.innerWidth, window.innerHeight ); camera.aspect = window.innerWidth / window.innerHeight; camera.updateProjectionMatrix(); }, false ); pen3D = { drawTrunk: function(root, size) { // root.skin = skin(0.5, 0.3, 0.2); root.add(new THREE.Mesh(new THREE.CylinderGeometry(size/12, size/10, size, 16), root.skin).translateY(size/2)); root.add(new THREE.Mesh(new THREE.SphereGeometry(size/12, 16), root.skin).translateY(size)); return root; }, drawLeaf: function(stem) { stem.skin.color.setRGB(0, 1, 0); stem.add(new THREE.Mesh(new THREE.CylinderGeometry(0, 0.02, 0.6), stem.skin) .rotateX(0.3).translateY(0.3)); stem.add(new THREE.Mesh(new THREE.CircleGeometry(0.2), stem.skin) .rotateX(0.3).translateY(0.4)); return stem; }, Thing: function() { THREE.Object3D.call(this); this.skin = new THREE.MeshLambertMaterial({ color: new THREE.Color(0.5, 0.3, 0.2), vertexColors: THREE.FaceColors, side: THREE.DoubleSide }) } }; pen3D.Thing.prototype = Object.create(THREE.Object3D.prototype); pen3D.Thing.prototype.tilt = pen3D.Thing.prototype.rotateX; pen3D.Thing.prototype.turn = pen3D.Thing.prototype.rotateY; pen3D.Thing.prototype.move = pen3D.Thing.prototype.translateY; pen3D.center = new pen3D.Thing; scene.add(pen3D.center); return pen3D; } 
 <script src="ajax/libs/three.js/r71/three.min.js"></script> 

First of all – setTimeout and setInterval is what should be used, because of javascript's callback-ish nature. If you want to use sleep() it's the control flow or the architecture of your code that is incorrect.

Having said that I suppose I still can help with two implementation of a sleep.

  1. faking synchronous run off the top of my head:

     //a module to do taht //dual-license: MIT or WTF [you can use it anyhow and leave my nickname in a comment if you want to] var _=(function(){ var queue=[]; var play=function(){ var go=queue.shift(); if(go){if(go.a){go.f();play();}else{setTimeout(play,go.t);}} } return { go:function(f){ queue.push({a:1,f:f}); }, sleep:function(t){ queue.push({a:0,t:t}); }, playback:play } })(); 

    [making playback automatic should also be possible]

     //usage _.go(function(){ //your code console.log('first'); }); _.sleep(5000); _.go(function(){ //your code console.log('next'); }); //this triggers the simulation _.playback(); 
  2. real synchronous run

I gave it a lot of thought one day and the only idea I had for a true sleep in javascript is technical.

a sleep function would have to be a synchronous AJAX call with a timeout set to the sleep value. That's all and an only way to have a real sleep()

Code taken from this link will not freeze comp. But it works only on ff.

  /** * Netscape compatible WaitForDelay function. * You can use it as an alternative to Thread.Sleep() in any major programming language * that support it while JavaScript it self doesn't have any built-in function to do such a thing. * parameters: * (Number) delay in millisecond */ function nsWaitForDelay(delay) { /** * Just uncomment this code if you're building an extention for Firefox. * Since FF3, we'll have to ask for user permission to execute XPCOM objects. */ netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect"); // Get the current thread. var thread = Components.classes["@mozilla.org/thread-manager;1"].getService(Components.interfaces.nsIThreadManager).currentThread; // Create an inner property to be used later as a notifier. this.delayed = true; /* Call JavaScript setTimeout function * to execute this.delayed = false * after it finish. */ setTimeout("this.delayed = false;", delay); /** * Keep looping until this.delayed = false */ while (this.delayed) { /** * This code will not freeze your browser as it's documented in here: * https://developer.mozilla.org/en/Code_snippets/Threads#Waiting_for_a_background_task_to_complete */ thread.processNextEvent(true); } }