什么是 JavaScript 版本的睡眠?

Is there a better way to engineer a sleep in JavaScript than the following pausecomp function (taken from here)?

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

This is not a duplicate of Sleep in JavaScript - delay between actions; I want a real sleep in the middle of a function, and not a delay before a piece of code executes.

转载于:https://stackoverflow.com/questions/951021/what-is-the-javascript-version-of-sleep

weixin_41568126
乱世@小熊 Probably you can do what you want with continuation passing style in JavaScript. Take a look at this article.
5 年多之前 回复
weixin_41568183
零零乙 The only purpose for a sleep is polling or waiting for a callback - setInterval and setTimeout do both better than this.
11 年多之前 回复
csdnceshi52
妄徒之命 This is a horrible solution - you're going to be chewing up processing cycles while doing nothing.
11 年多之前 回复
csdnceshi58
Didn"t forge It's to set in the middle of a while, if i use setTimeout the while will continue to process and queue more setTimeouts which will eventually be running at the same time and making a bit of concurrency between themselves
11 年多之前 回复

30个回答

2017 update

Since 2009 when this question was asked, JavaScript has evolved significantly. All other answers are now obsolete or overly complicated. Here is the current best practice:

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

async function demo() {
  console.log('Taking a break...');
  await sleep(2000);
  console.log('Two seconds later');
}

demo();

This is it. await sleep(<duration>).

You can try this code live on Runkit. Note that,

  1. await can only be executed in functions prefixed with the async keyword. Runkit wraps your code in an async function before executing it.
  2. await only pauses the current async function

Two new JavaScript features helped write this actual "sleep" function:

Compatibility

If for some reason you're using Node older than 7, or are targeting old browsers, async/await can still be used via Babel (a tool that will transpile JavaScript + new features into plain old JavaScript), with the transform-async-to-generator plugin. Run

npm install babel-cli --save

Create .babelrc with:

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

Then run your code with

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

But again, you don't need this if you're using Node 7 or later, or if you're targeting modern browsers.

</div>
weixin_41568184
叼花硬汉 Personal preference I guess, I don't find the one in the answer clearer.
接近 2 年之前 回复
weixin_41568208
北城已荒凉 what are the advantages of that syntax vs. the clear function definition from the answer?
接近 2 年之前 回复
weixin_41568110
七度&光 why not use promisify?
接近 2 年之前 回复
weixin_41568174
from.. I agree. However, that was the question, extremely clearly.
大约 2 年之前 回复
csdnceshi68
local-host JavaScript, being a single-threaded language, is not well-suited for "real" sleep, since it runs on the same thread as the UI and would cause unresponsive web pages.
大约 2 年之前 回复
weixin_41568184
叼花硬汉 Oneliner for the function declaration: const sleep = ms => new Promise(resolve => setTimeout(resolve, ms))
大约 2 年之前 回复
csdnceshi66
必承其重 | 欲带皇冠 oneliner await new Promise(r => setTimeout(() => r(), 2000));
2 年多之前 回复
csdnceshi69
YaoRaoLov Google Apps Script returns Syntax error at the line where the sleep function is defined. (in Chrome 59.0.3071.115 (Official Build) (32-bit))
大约 3 年之前 回复
weixin_41568183
零零乙 - the transpiler handles arrow functions as well as async/await (which would cause IE to vomit blood anyway)
3 年多之前 回复
csdnceshi74
7*4 While Promises can be polyfilled, arrow functions cannot. This is not a viable solution for those having to support IE.
3 年多之前 回复
weixin_41568174
from.. This is not "real sleep" and does not answer the question. The person who asked made a clear distinct between stackoverflow.com/questions/758688/sleep-in-javascript and his question. In real sleep no other code can be executed (unless in other thread). This answer is good for the other question.
3 年多之前 回复
weixin_41568208
北城已荒凉 the majority of modern web development uses transpilers, so native browser support matters less than cleaner and more future-proof code. Anyway, see caniuse.
3 年多之前 回复
csdnceshi73
喵-见缝插针 What is the current browser support for this? I wouldn't consider the previous solutions to be "obsolete" until this solution is supported by the vast majority of browsers, or at least all of the common ones. On the contrary, I would consider this solution interesting but unusable/impractical until it has widespread support.
3 年多之前 回复
csdnceshi52
妄徒之命 Great stuff here. I wonder, how does this affects or relates with the modern browsers "active" / "inactive" states after JS calls the "sleep" mode? Can the browser block the sleep as expected for general JS, to recall later when becomes "active", or does it have a different behavior?
接近 4 年之前 回复

For the love of $DEITY please do not make a busy-wait sleep function. setTimeout and setInterval do everything you need.

csdnceshi54
hurriedly% It doesn't "lock it up" It starts all the timeouts as fast as it can, and then after the 1.5 second delay, they all try to run at once and only one actually happens. I DID need a delay between downloads in order to actually get them. What does "split it up" mean? Write separate code for each link instead of running a loop? That would take longer than the twelve hundred clicks I was trying to avoid. What finally worked was changing the delay each time: setTimeout({}, 1500*i++);
2 年多之前 回复
csdnceshi60
℡Wang Yan This is a classical example of something people think they need sleep for when they don't. You don't need to busywait-lockup the JS engine, you need to split up your processing across setTimeout.
2 年多之前 回复
csdnceshi54
hurriedly% My usage is a loop to download hundreds of PDFs from a database whose admin refuses to provide the data in a sensible format. The loop needs a delay between files to ensure little or no overlap.
2 年多之前 回复
csdnceshi56
lrony* and what if we wanted to use it in a for loop?
5 年多之前 回复
csdnceshi60
℡Wang Yan Any context in which closures are not JS 101 needs a full curriculum redesign, stat.
6 年多之前 回复
weixin_41568208
北城已荒凉 Completely disagree, closures aren't JS 101. If a novice is looking to write a purely synchronous and simple script, a function like sleep() might come in handy.
6 年多之前 回复
csdnceshi60
℡Wang Yan If syntactic closure is still scaring one, one seriously needs to buckle down and work through Node 101.
6 年多之前 回复
weixin_41568208
北城已荒凉 I think many of us might be forgetting that JavaScript isn't a browser-only language. This dude might be creating a Node command line utility that requires a brief pause without needing to deal with all the variable scoping issues that come with setTimeout.
6 年多之前 回复
csdnceshi60
℡Wang Yan Since Javascript only supports synchronous sleep by way of hammering the CPU as hard as it possibly can until the sleep duration is over, my sole recommendation for that situation is "redesign until you no longer need synchronous sleep".
大约 9 年之前 回复
csdnceshi53
Lotus@ Unless you need the sleep to be synchronous, in which case this is a completely valid question.
大约 9 年之前 回复
csdnceshi50
三生石@ What would that piece of code not hold back in the JavaScript engine?
11 年多之前 回复
weixin_41568127
?yb? I sometimes miss a real "sleep", but messing around with setTimeout is still better than actively waiting (like the above while loop). A real sleep function does however not need to freeze the JavaScript engine, but a busy-wait would max out a single CPU core. (And eat up precious battery time of mobile users)
11 年多之前 回复
csdnceshi74
7*4 Well not quite everything: setInterval does a much better impression of polling.
11 年多之前 回复
csdnceshi59
ℙℕℤℝ I agree. Wouldn't a real "sleep" freeze up the whole javascript engine...
11 年多之前 回复

Only for debug/dev , I post this if it's useful to someone

Interesting stuff, in Firebug ( & probably other js consoles ), nothing happen after hitting enter, only after the sleep duration specified (...)

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

Example of use:

function sleepThenAct(){ sleepFor(2000); console.log("hello js sleep !"); }
weixin_41568196
撒拉嘿哟木头 This actually solves my issue, because that's exactly what I need: busy wait for debug purposes. I can't use await, I don't know why, it doesn't compile. I'm not a js expert, so I better just use this code, thanks!
大约 2 年之前 回复
csdnceshi53
Lotus@ The solution is not good, but in some places async/await it's not responsive unfortunately, and we have to use it mandatorily.
2 年多之前 回复
weixin_41568183
零零乙 This is useful, and perhaps the ONLY way to sleep, within a command-line javascript application, because async/await is not helpful.
2 年多之前 回复
csdnceshi52
妄徒之命 NEVER DO THIS. This will make the CPU to hit 100% on the core that it executes and will block it.
接近 3 年之前 回复
weixin_41568127
?yb? it's not tricky at all. As Kee said, it's useful for testing. If you just want to run C after B after A, using promises or callbacks leads you straight to hell. I use it to wait for exec to finish doing something. It means that I can write utility functions and call them as part of a simple script, instead of putting whole chunks of code in callbacks.
大约 3 年之前 回复
csdnceshi59
ℙℕℤℝ that's true, it's so tricky to come up with a proper example that it probably deserves its own question!
大约 4 年之前 回复
csdnceshi68
local-host I'd be hard pressed to come up with an example of this technique ever being the correct way (or even direction) to solve a problem, regardless if dev or prod.
大约 4 年之前 回复
csdnceshi59
ℙℕℤℝ That's one of the reasons why I upvoted it. I find hilarious that he optimized his busy waiting loop
大约 4 年之前 回复
csdnceshi59
ℙℕℤℝ That's why it says only for debug/dev... rolleyes
大约 4 年之前 回复
csdnceshi68
local-host Busy waiting, really? In JS? For seconds? If I catch a website doing this, it will be blocked.
大约 4 年之前 回复
weixin_41568126
乱世@小熊 github.com/JDMcKinstry/JavaScript-Delay-Method/blob/master/…
大约 4 年之前 回复
csdnceshi70
笑故挽风 This is not an answer. It's exactly the same as the code in the question, except slightly shorter.
5 年多之前 回复

I know this is a bit of an old question, but if (like me) you're using Javascript with Rhino, you can use...

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.
   */
}
csdnceshi57
perhaps? Incorrect. It is JavaScript using Rhino (at the time, it could equally be Nashorn these days)
2 年多之前 回复
csdnceshi77
狐狸.fox This is Java not Javascript
2 年多之前 回复
csdnceshi57
perhaps? Yes, a call to Java's thread sleep.
5 年多之前 回复
csdnceshi58
Didn"t forge Is this a call to Java?
5 年多之前 回复

(See the updated answer for 2016)

I think it's perfectly reasonable to want to perform an action, wait, then perform another action. If you are used to writing in multi-threaded languages, you probably have the idea of yielding execution for a set amount of time until your thread wakes up.

The issue here is that JavaScript is a single-thread event-based model. While in a specific case, it might be nice to have the whole engine wait for a few seconds, in general it is bad practice. Suppose I wanted to make use of your functions while writing my own? When I called your method, my methods would all freeze up. If JavaScript could somehow preserve your function's execution context, store it somewhere, then bring it back and continue later, then sleep could happen, but that would basically be threading.

So you are pretty much stuck with what others have suggested -- you'll need to break your code up into multiple functions.

Your question is a bit of a false choice, then. There is no way to sleep in the way you want, nor should you pursue the solution you suggest.

csdnceshi63
elliott.david I agree why sleep() isn't possible in JS, and that most of the time there are better ways to do things. But I'd still consider the way the engine ties all things up to be a design flaw; there's no reason the language couldn't have a sleep() function limited to a specific script, page, or function without the engine clobbering the CPU and freezing the app like a maniac. It's 2015 and you shouldn't be able to crash an entire web browser with while(1). We have Flash for things like that.
大约 5 年之前 回复
csdnceshi70
笑故挽风 Calling javascript single-threaded is a but of a myth. While it may be technically correct, functionally it acts like a multithreaded langauge. Simulating a fork() is trivially easy, and although yield() isn't really implementable, you can get pretty close by using shared memory to lock/semaphore. For the average programmer, it makes sense to treat it as multi-threaded; the technical name only matters to the developers of the language.
5 年多之前 回复
weixin_41568127
?yb? There is one situation where timeouts simply don't solve the problem, no matter how much you refactor: if you're running server-side, the client is waiting for the data, and you don't have direct access to the connection to pass it to the timeout callback. For instance, in meteor, you could be running in a method. In that case, you should consider using a future, as described here: stackoverflow.com/questions/12569712/…
大约 6 年之前 回复
csdnceshi50
三生石@ Try Hypnotic, which follows this idea: coolwanglu.github.io/hypnotic/web/demo.html
接近 7 年之前 回复
csdnceshi75
衫裤跑路 A sleep can be perfectly implemented in JavaScript allbeit not with real-time precision. After all it is an event based system. If async calls are completed an event is triggered. I see no reason why the same can't be possible when a sleep() is issued after which control is returned to the browser until the sleeping is over, returning control to the calling function. And yes, I also agree that sometimes sleeping is handy especially when developers BEFORE you screwed up the design so badly that YOU have no other way out besides completely refactoring for which you have no time
接近 7 年之前 回复
weixin_41568174
from.. This is not a correct answer at all. If Javascript does not have a sleep function, it is only because ECMAScript does not require it. It is a design choice by the body responsible for the design of Javascript. It could have been made that the Javascript run time waits a given amount of time before running the next line of code, but it was chosen not to.
大约 7 年之前 回复

In JavaScript, I rewrite every function so that it can end as soon as possible. You want the browser back in control so it can make your DOM changes.

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

I am going to edit this answer because i found this as useful:

The infamous sleep, or delay, function within any language is much debated. Some will say that there should always be a signal or callback to fire a given functionality, others will argue that sometimes an arbitrary moment of delay is useful. I say that to each their own and one rule can never dictate anything in this industry.

Writing a sleep function is simple and made even more usable with JavaScript Promises:

// sleep time expects milliseconds
function sleep (time) {
  return new Promise((resolve) => setTimeout(resolve, time));
}

// Usage!
sleep(500).then(() => {
    // Do something after the sleep!
});
csdnceshi56
lrony* "I'm 5 levels deep in a for loop. I want to BLOCK execution." ...How about alert("hi, i'm blocking execution");? ...When the alert pops up, and without dismissing it, I can still access Chrome's console and do debugging.
大约 4 年之前 回复
csdnceshi62
csdnceshi62 this can be done using JavaScript Promises. I have added the answer. this works.
大约 4 年之前 回复
weixin_41568127
?yb? A good while ago, I flagged this as being "not an answer", only to have the author of this answer (@Nosredna, I'm looking at you) to decline this flag with a cheap-ass "declined - Seriously?". Clearly @Nosredna has a conflict of interest--he would rather preserve his upvotes than help other users/Web browsers find the best answer to this question. This is the first time I've noticed a misuse of bureaucratic power on a SE site, but I will pay more attention. This kind of BULLSHIT is exactly why I stopped contributing to WikiMedia projects a long time ago!
4 年多之前 回复
csdnceshi57
perhaps? setTimeout doesnt SLEEP in the middle of your function as you've stated. Your function continues executing. Everything else inside the setTimeout will get executed later on.
接近 5 年之前 回复
weixin_41568183
零零乙 and what if we wanted to use it in a for loop?
5 年多之前 回复
csdnceshi73
喵-见缝插针 True (synchronous) sleep is useful in testing, e.g. to simulate a long-running JS task. Many eventing bugs arise due to heavy JS tasks (e.g. backend requests with large payloads that need processing or unbatched processing on very large pages). Synchronous sleep is useful for testing + repro in such cases.Should never run in production code, but far from useless.
5 年多之前 回复
csdnceshi80
胖鸭 the original answer just referred to setTimeout and is ok, because it's just an opinion. But the edit misdirects the reader to think that there is a equiv sleep, which is just a call to setTimeout... it's a bad joke really because it wastes ppl's time in reading and understanding... essentially nothing.
接近 6 年之前 回复
csdnceshi54
hurriedly% am I the only one to notice the sleep function is identical to just using setTimeout (minus the reversed arguments) ??
大约 6 年之前 回复
csdnceshi50
三生石@ The function assigned to the setTimeout is put onto an event queue. JavaScript is inherently single-threaded. If there’s at least one event on the queue that’s eligible to “fire” (like a 3000ms timeout that was set 4000ms ago), the "javascript VM" will pick one and call its handler (function callback). The point is that the actual call will unlikely be precisely when you requested it (say 3000 milliseconds later), it might be 3001, 3002 or even quite a bit later depending on number and nature of other events on the queue, & the duration of their callbacks
6 年多之前 回复
weixin_41568131
10.24 To call functions with parameters using the same code above use for example: foobar_cont_2.bind(this, "value")) to call the function foobar_cont_2(xXx)
6 年多之前 回复
csdnceshi60
℡Wang Yan I'm making a .html (no hosting) but sadly, all the familiars I send them to use Chrome ;(
6 年多之前 回复
csdnceshi67
bug^君 Try this almost answer: Hypnotic. coolwanglu.github.io/hypnotic/web/demo.html
接近 7 年之前 回复
csdnceshi72
谁还没个明天 good comment Jelgab, you can tell you are a developer. In case someone want's to block the browser on an ajax call, it would be so simple to switch off async on that call: $.ajax({ 'async': false });
接近 7 年之前 回复
weixin_41568196
撒拉嘿哟木头 How would one approach the following cases: 1. During testing the developer wants to simulate that clicking a button calls a process that takes real long and requirements do not allow to either change the way the process is called or to call it asynchronously 2. After clicking a button, some changes happen on the page (like a "please wait..." message that the user will randomly see depending on how busy is the server at the moment but right now the developer wants to visually test the message simulating the server is busy.
7 年多之前 回复
csdnceshi58
Didn"t forge ok @Morg, you're right, but as I saw the title was related to javascript and sleep I though it was not only a solution for a web page, I could ask something by myself instead of asking in a comment. Thanks for your suggestion.
8 年多之前 回复
csdnceshi69
YaoRaoLov ; my bad, I probably used the wrong words. Your question is unrelated to the question that was answered here, trying to extend the scope by asking a question in the comments is a bad idea, you should create a new question about node.js or w/e server-side js technology you're using in order to get a real answer.
8 年多之前 回复
csdnceshi58
Didn"t forge sorry to disagree with you, I need a solution like this in an environment different than an webpage, please, if you don't like my comment please skip it, I come here to find answers not to read comments like yours. Thanks.
8 年多之前 回复
weixin_41568126
乱世@小熊 loop-safe version: for(i=0; i<5; i++) { (function(i) { setTimeout(function() { console.log(i); }, 1000*i); })(i); }
8 年多之前 回复
csdnceshi68
local-host this is not an answer to the question.
接近 9 年之前 回复
csdnceshi76
斗士狗 yes, we understand how to make async calls, this doesn't help us sleep(). I want my calls to be made in a certain order, and to have the data back in a certain order. I'm 5 levels deep in a for loop. I want to BLOCK execution. A true sleep method would not "slow down the browser", sleep hands control back to the browser and any other threads that want CPU time while it is still blocking.
接近 9 年之前 回复
csdnceshi76
斗士狗 if the code is not intended to be used in a webpage, have the host's object model implement a sleep method. -- I think the question is geared towards the DOM which is exposed to javascript running on web pages.
接近 9 年之前 回复
csdnceshi75
衫裤跑路 the function foobar_con takes the value of el at the moment of invocation of function foobar_con, but not unfortunately of the function foobar. Good example is a loop where el is changing: all the delayed function invocations of foobar_con will be with the maximal value of el.
9 年多之前 回复
csdnceshi58
Didn"t forge ok, and what if the code is not intended to be used in a webpage?
大约 10 年之前 回复
csdnceshi77
狐狸.fox By way of closure. function foobar(el) { setTimeout(function() { foobar_cont(el); }, 5000); }
10 年多之前 回复
csdnceshi65
larry*wei this solution doesn't work if you have any state variables. If the function you're trying to sleep has any parameters. For example, how can one do fuction foobar(el){ setTimeout(foobar_cont(el),5000); } ??? I haven't figured that out yet.
10 年多之前 回复

I agree with the other posters, a busy sleep is just a bad idea.

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.

weixin_41568134
MAO-EYE To improve upon Izkata's code, I needed to add .bind to the anonymous function to pass the index value i: var delay =3000; for (var i=0; i<urlList.length; i++){ setTimeout(function (i){window.open(urlList[i])}.bind(null,i), (i * delay)); }
2 年多之前 回复
weixin_41568127
?yb? This is not an answer to the question. Even if it's a Terrible Idea™ to pause ALL execution, that is what is asked and it's not what this code does.
大约 4 年之前 回复
csdnceshi78
程序go Of course it does, because the point of setTimeout() is to prevent the browser from locking up by running the code asychronously. Put the console.log() inside foo_continue() in the setTimeout version and you get the same result.
5 年多之前 回复
weixin_41568208
北城已荒凉 Have you tried to us this with foo(index) { console.log(c[index-1]); and foo_continue(index) { c[index]=index; }? You will see that the results differ whether you use setTimeout or the fictitious sleep() command.
5 年多之前 回复
csdnceshi78
程序go No, you'd use a closure. For example: function foo(index) { setTimeout(function() { foo_continue(index); }, 10000); } and for(var X = 0; X < 3;X++) { foo(X); } - the value of X is passed into foo, which then gets reused under the name index when foo_continue is eventually called.
6 年多之前 回复
csdnceshi53
Lotus@ -1 for this. Again, this does not answer the question. This is more an answer for a question like "How to execute a function asynchronously" which is very much different from "How to block a code execution".
7 年多之前 回复
csdnceshi50
三生石@ In the example at the bottom of this blog post, I use variables attached to the function to hold the current progress. dreaminginjavascript.wordpress.com/2008/08/02/…
11 年多之前 回复
csdnceshi50
三生石@ Any time I have to do it, I comment heavily. JavaScript is meant to run as an event handler, and the pieces are supposed to execute quickly. Making a computation-intensive RIA in JavaScript is certainly possible, but you have to give a lot of time to the browser or your UI gets sluggish. IE, of course, is the worst.
11 年多之前 回复
csdnceshi79
python小菜 Touché. I mean, it would still be possible, but ugly and hackish in that case. You could also use some static boolean state variables, but that's also pretty hackish.
11 年多之前 回复
csdnceshi50
三生石@ Yeah. Where this gets tricky is when you have a loop, or a nested loop even. You have to abandon your for loops and have counters instead.
11 年多之前 回复

Here's a simple solution using a synchronous XMLHttpRequest:

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

contents of sleep.php:

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

Now call it with: sleep(5);

weixin_41568208
北城已荒凉 It was funny :-D
2 年多之前 回复
csdnceshi74
7*4 This is actually a pretty good idea IMO. Although I don't think the sleep API (Request URL) should be public as it can be abused.
4 年多之前 回复
weixin_41568126
乱世@小熊 this WILL work, though. :-)
4 年多之前 回复
csdnceshi52
妄徒之命 Unique approach, though unfortunately non-async XMLHttpRequests are deprecated and will be removed in the future. Which is funny, because that fact is what led me to this question in the first place.
5 年多之前 回复
csdnceshi65
larry*wei Use setTimeout() if that works, but if doing so means unraveling 1000 lines of callbacks this might start not looking like a joke.
5 年多之前 回复
csdnceshi76
斗士狗 I assume this is a joke... +1!
接近 6 年之前 回复
function sleep(milliseconds) {
  var start = new Date().getTime();
  for (var i = 0; i < 1e7; i++) {
    if ((new Date().getTime() - start) > milliseconds){
      break;
    }
  }
}
csdnceshi80
胖鸭 Not a good solution - using this in Selenium's JavaScriptExecutor hangs my Chrome browser about 50% of the time on a 2104 MacBook Pro.
5 年多之前 回复
csdnceshi74
7*4 It's the same as the real question. Not much point making it the real answer.
6 年多之前 回复

It can be done using Java's sleep method. I've tested it in FF and IE and it doesn't lock the computer, chew up resources, or cause endless server hits. Seems like a clean solution to me.

First you have to get Java loaded up on the page and make its methods available. To do that, I did this:

<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" />

Then, all you have to do when you want a painless pause in your JS is:

java.lang.Thread.sleep(xxx)

Where xxx is time in milliseconds. In my case (by way of justification), this was part of back-end order fulfillment at a very small company and I needed to print an invoice that had to be loaded from the server. I did it by loading the invoice (as a webpage) into an iFrame and then printing the iFrame. Of course, I had to wait until the page was fully loaded before I could print, so the JS had to pause. I accomplished this by having the invoice page (in the iFrame) change a hidden form field on the parent page with the onLoad event. And the code on the parent page to print the invoice looked like this (irrelevant parts cut for clarity):

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();

So the user pushes the button, the script loads the invoice page, then waits, checking every quarter second to see if the invoice page is finished loading, then pops up the print dialog for the user to send it to the printer. QED.

csdnceshi73
喵-见缝插针 This depends on Java Applets which is deprecated.
4 年多之前 回复
csdnceshi67
bug^君 Seems quite monstrous soulution when considering the simple thing author wanted to achieve.
7 年多之前 回复
共30条数据 1 3 尾页
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问