什么是 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.
4 年多之前 回复
weixin_41568183
零零乙 The only purpose for a sleep is polling or waiting for a callback - setInterval and setTimeout do both better than this.
10 年多之前 回复
csdnceshi52
妄徒之命 This is a horrible solution - you're going to be chewing up processing cycles while doing nothing.
10 年多之前 回复
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
10 年多之前 回复

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.
大约一年之前 回复
weixin_41568208
北城已荒凉 what are the advantages of that syntax vs. the clear function definition from the answer?
大约一年之前 回复
weixin_41568110
七度&光 why not use promisify?
大约一年之前 回复
weixin_41568174
from.. I agree. However, that was the question, extremely clearly.
大约一年之前 回复
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.
大约一年之前 回复
weixin_41568184
叼花硬汉 Oneliner for the function declaration: const sleep = ms => new Promise(resolve => setTimeout(resolve, ms))
大约一年之前 回复
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))
2 年多之前 回复
weixin_41568183
零零乙 - the transpiler handles arrow functions as well as async/await (which would cause IE to vomit blood anyway)
2 年多之前 回复
csdnceshi74
7*4 While Promises can be polyfilled, arrow functions cannot. This is not a viable solution for those having to support IE.
2 年多之前 回复
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?
大约 3 年之前 回复

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++);
一年多之前 回复
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.
一年多之前 回复
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.
一年多之前 回复
csdnceshi56
lrony* and what if we wanted to use it in a for loop?
4 年多之前 回复
csdnceshi60
℡Wang Yan Any context in which closures are not JS 101 needs a full curriculum redesign, stat.
5 年多之前 回复
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.
5 年多之前 回复
csdnceshi60
℡Wang Yan If syntactic closure is still scaring one, one seriously needs to buckle down and work through Node 101.
5 年多之前 回复
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.
5 年多之前 回复
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".
大约 8 年之前 回复
csdnceshi53
Lotus@ Unless you need the sleep to be synchronous, in which case this is a completely valid question.
大约 8 年之前 回复
csdnceshi50
三生石@ What would that piece of code not hold back in the JavaScript engine?
10 年多之前 回复
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)
10 年多之前 回复
csdnceshi74
7*4 Well not quite everything: setInterval does a much better impression of polling.
10 年多之前 回复
csdnceshi59
ℙℕℤℝ I agree. Wouldn't a real "sleep" freeze up the whole javascript engine...
10 年多之前 回复

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!
大约一年之前 回复
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.
一年多之前 回复
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.
接近 2 年之前 回复
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.
大约 2 年之前 回复
csdnceshi59
ℙℕℤℝ that's true, it's so tricky to come up with a proper example that it probably deserves its own question!
大约 3 年之前 回复
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.
大约 3 年之前 回复
csdnceshi59
ℙℕℤℝ That's one of the reasons why I upvoted it. I find hilarious that he optimized his busy waiting loop
大约 3 年之前 回复
csdnceshi59
ℙℕℤℝ That's why it says only for debug/dev... rolleyes
大约 3 年之前 回复
csdnceshi68
local-host Busy waiting, really? In JS? For seconds? If I catch a website doing this, it will be blocked.
大约 3 年之前 回复
weixin_41568126
乱世@小熊 github.com/JDMcKinstry/JavaScript-Delay-Method/blob/master/…
大约 3 年之前 回复
csdnceshi70
笑故挽风 This is not an answer. It's exactly the same as the code in the question, except slightly shorter.
4 年多之前 回复

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)
一年多之前 回复
csdnceshi77
狐狸.fox This is Java not Javascript
一年多之前 回复
csdnceshi57
perhaps? Yes, a call to Java's thread sleep.
4 年多之前 回复
csdnceshi58
Didn"t forge Is this a call to Java?
4 年多之前 回复

(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.
大约 4 年之前 回复
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.
4 年多之前 回复
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/…
大约 5 年之前 回复
csdnceshi50
三生石@ Try Hypnotic, which follows this idea: coolwanglu.github.io/hypnotic/web/demo.html
接近 6 年之前 回复
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
接近 6 年之前 回复
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.
大约 6 年之前 回复

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.
大约 3 年之前 回复
csdnceshi62
csdnceshi62 this can be done using JavaScript Promises. I have added the answer. this works.
3 年多之前 回复
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!
3 年多之前 回复
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.
接近 4 年之前 回复
weixin_41568183
零零乙 and what if we wanted to use it in a for loop?
4 年多之前 回复
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.
接近 5 年之前 回复
csdnceshi54
hurriedly% am I the only one to notice the sleep function is identical to just using setTimeout (minus the reversed arguments) ??
5 年多之前 回复
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
5 年多之前 回复
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)
5 年多之前 回复
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
接近 6 年之前 回复
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 });
接近 6 年之前 回复
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.
6 年多之前 回复
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.
7 年多之前 回复
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.
7 年多之前 回复
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.
7 年多之前 回复
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.
接近 8 年之前 回复
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.
大约 8 年之前 回复
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.
大约 8 年之前 回复
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.
8 年多之前 回复
csdnceshi58
Didn"t forge ok, and what if the code is not intended to be used in a webpage?
大约 9 年之前 回复
csdnceshi77
狐狸.fox By way of closure. function foobar(el) { setTimeout(function() { foobar_cont(el); }, 5000); }
9 年多之前 回复
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.
9 年多之前 回复

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)); }
一年多之前 回复
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.
大约 3 年之前 回复
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.
4 年多之前 回复
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.
4 年多之前 回复
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".
6 年多之前 回复
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/…
10 年多之前 回复
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.
10 年多之前 回复
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.
10 年多之前 回复
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.
10 年多之前 回复

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
一年多之前 回复
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.
3 年多之前 回复
weixin_41568126
乱世@小熊 this WILL work, though. :-)
3 年多之前 回复
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.
4 年多之前 回复
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!
接近 5 年之前 回复
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.
4 年多之前 回复
csdnceshi74
7*4 It's the same as the real question. Not much point making it the real answer.
5 年多之前 回复

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.
3 年多之前 回复
csdnceshi67
bug^君 Seems quite monstrous soulution when considering the simple thing author wanted to achieve.
6 年多之前 回复
共30条数据 1 3 尾页
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
如何查看当前的javascript版本?
-
qui页面框架中的js版本太低怎么解决
-
windows版本下怎么降低已安装了的node.js版本
-
javascript怎么创建对象?js的对象和java有什么不同?
-
简单的js的语句判断问题
-
同一个文件下php代码接收js代码的变量,是什么原理?
-
这个js代码是属于什么框架?
-
新建Vue项目卡在描述 换了好多node.js版本
-
Chrome插件popup.js的onclick无效
-
修改js源文件无效,请问是什么原因
-
请教JS达人:JavaScript的单线程和AJAX的异步操作是神马情况啊?
-
require js在家js文件,怎么给js文件增加版本号
-
一个js文件怎么获取另一个js文件里更新后的变量值?
-
在使用InDesign和prcc的时候出现node.js:sever-side javascript 已停止工作
-
js 中的for循环 怎么每循环一次睡眠3秒???
-
JavaScript中对象的引用是什么意思?主要是这个引用是什么意思?
-
javascript中的eval是干什么的?和asp.net的Eval有什么不同
-
使用Modernizr.js的问题
-
Nw.js打包Vue项目成exe文件后,运行exe文件2个小时左右出现闪退问题,没有报错什么的,有哪位大神知道怎么回事吗?
-
javascript简单的问题,想要c币的都来回答:怎么在js网页中实现
-
程序员实用工具网站
目录 1、搜索引擎 2、PPT 3、图片操作 4、文件共享 5、应届生招聘 6、程序员面试题库 7、办公、开发软件 8、高清图片、视频素材网站 9、项目开源 10、在线工具宝典大全 程序员开发需要具备良好的信息检索能力,为了备忘(收藏夹真是满了),将开发过程中常用的网站进行整理。 1、搜索引擎 1.1、秘迹搜索 一款无敌有良心、无敌安全的搜索引擎,不会收集私人信息,保...
我花了一夜用数据结构给女朋友写个H5走迷宫游戏
起因 又到深夜了,我按照以往在csdn和公众号写着数据结构!这占用了我大量的时间!我的超越妹妹严重缺乏陪伴而 怨气满满! 而女朋友时常埋怨,认为数据结构这么抽象难懂的东西没啥作用,常会问道:天天写这玩意,有啥作用。而我答道:能干事情多了,比如写个迷宫小游戏啥的! 当我码完字准备睡觉时:写不好别睡觉! 分析 如果用数据结构与算法造出东西来呢? ...
别再翻了,面试二叉树看这 11 个就够了~
写在前边 数据结构与算法: 不知道你有没有这种困惑,虽然刷了很多算法题,当我去面试的时候,面试官让你手写一个算法,可能你对此算法很熟悉,知道实现思路,但是总是不知道该在什么地方写,而且很多边界条件想不全面,一紧张,代码写的乱七八糟。如果遇到没有做过的算法题,思路也不知道从何寻找。面试吃了亏之后,我就慢慢的做出总结,开始分类的把数据结构所有的题型和解题思路每周刷题做出的系统性总结写在了 Github...
让程序员崩溃的瞬间(非程序员勿入)
今天给大家带来点快乐,程序员才能看懂。 来源:https://zhuanlan.zhihu.com/p/47066521 1. 公司实习生找 Bug 2.在调试时,将断点设置在错误的位置 3.当我有一个很棒的调试想法时 4.偶然间看到自己多年前写的代码 5.当我第一次启动我的单元测试时 ...
七个开源的 Spring Boot 前后端分离项目,一定要收藏!
前后端分离已经在慢慢走进各公司的技术栈,根据松哥了解到的消息,不少公司都已经切换到这个技术栈上面了。即使贵司目前没有切换到这个技术栈上面,松哥也非常建议大家学习一下前后端分离开发,以免在公司干了两三年,SSH 框架用的滚瓜烂熟,出来却发现自己依然没有任何优势! 其实前后端分离本身并不难,后段提供接口,前端做数据展示,关键是这种思想。很多人做惯了前后端不分的开发,在做前后端分离的时候,很容易带进来一...
用Python分析2000款避孕套,得出这些有趣的结论
到现在为止,我们的淘宝教程已经写到了第四篇,前三篇分别是: 第一篇:Python模拟登录淘宝,详细讲解如何使用requests库登录淘宝pc端。 第二篇:淘宝自动登录2.0,新增Cookies序列化,教大家如何将cookies保存起来。 第三篇:Python爬取淘宝商品避孕套,教大家如何爬取淘宝pc端商品信息。 今天,我们来看看淘宝系列的第四篇 我们在上一篇的时候已经将淘宝数据爬取下来了,...
接私活必备的 10 个开源项目!
点击蓝色“GitHubDaily”关注我加个“星标”,每天下午 18:35,带你逛 GitHub!作者 | SevDot来源 | http://1t.click/VE8W...
阿里资深工程师教你如何优化 Java 代码!
作者 | 王超 责编 | 伍杏玲 明代王阳明先生在《传习录》谈为学之道时说: 私欲日生,如地上尘,一日不扫,便又有一层。着实用功,便见道无终穷,愈探愈深,必使精白无一毫不彻方可。 代码中的"坏味道",如"私欲"如"灰尘",每天都在增加,一日不去清除,便会越累越多。如果用功去清除这些"坏味道",不仅能提高自己的编码水平,也能使代码变得"精白无一毫不彻"。这里,整理了日常工作中的一...
GitHub开源的10个超棒后台管理面板
目录 1、AdminLTE 2、vue-Element-Admin 3、tabler 4、Gentelella 5、ng2-admin 6、ant-design-pro 7、blur-admin 8、iview-admin 9、material-dashboard 10、layui 项目开发中后台管理平台必不可少,但是从零搭建一套多样化后台管理并不容易,目前有许多开源、免费、...
100 个网络基础知识普及,看完成半个网络高手
欢迎添加华为云小助手微信(微信号:HWCloud002或HWCloud003),输入关键字“加群”,加入华为云线上技术讨论群;输入关键字“最新活动”,获取华为云最新特惠促销。华为云诸多技术大咖、特惠活动等你来撩! 1)什么是链接? 链接是指两个设备之间的连接。它包括用于一个设备能够与另一个设备通信的电缆类型和协议。 2)OSI 参考模型的层次是什么? 有 7 个 OSI 层:物理...
Google离开我们快十年了
2010年1月13日,Google离开中国。掐指算来,Google已经离开我们快十年了。2010年是个特殊的年份,这一年还发生了3Q大战。为什么诸多大事都发生在2010年...
面试官的HTTP五连问法?我竟然回答不上来...
作者丨松若章来源丨http://1t.click/ataf曾经有这么一道经典面试题:从 URL 在浏览器被被输入到页面展现的过程中发生了什么?相信大多数准备过的同学都能回...
中国最顶级的一批程序员,从首富到首负!
过去的20年是程序员快意恩仇的江湖时代通过代码,实现梦想和财富有人痴迷于技术,做出一夜成名的产品有人将技术变现,创办企业成功上市这些早一代的程序员们创造的奇迹引发了一浪高...
为什么面向对象糟透了?
又是周末,编程语言“三巨头”Java, Lisp 和C语言在Hello World咖啡馆聚会。服务员送来咖啡的同时还带来了一张今天的报纸, 三人寒暄了几句, C语言翻开了...
分享靠写代码赚钱的一些门路
作者 mezod,译者 josephchang10如今,通过自己的代码去赚钱变得越来越简单,不过对很多人来说依然还是很难,因为他们不知道有哪些门路。今天给大家分享一个精彩...
对计算机专业来说学历真的重要吗?
我本科学校是渣渣二本,研究生学校是985,现在毕业五年,校招笔试、面试,社招面试参加了两年了,就我个人的经历来说下这个问题。 这篇文章很长,但绝对是精华,相信我,读完以后,你会知道学历不好的解决方案,记得帮我点赞哦。 先说结论,无论赞不赞同,它本质就是这样:对于技术类工作而言,学历五年以内非常重要,但有办法弥补。五年以后,不重要。 目录: 张雪峰讲述的事实 我看到的事实 为什么会这样 ...
在线就能用的Linux我给你找好了
来源:公众号【编程珠玑】 作者:守望先生 网站:https://www.yanbinghu.com 前言 是不是不想装虚拟机,还想体验一下Linux?是不是自己的电脑不在,又想搞事情?今天给大家推荐几个在线就可以玩的Linux环境以及学习Shell的地方。 在线Linux环境 如果你不想安装虚拟机,这里提供几个在线就能把玩Linux的网站,他们不需要注册用户,可以直接使用。 Unix...
世界上最好的学习法:费曼学习法
你是否曾幻想读一遍书就记住所有的内容?是否想学习完一项技能就马上达到巅峰水平?除非你是天才,不然这是不可能的。对于大多数的普通人来说,可以通过笨办法(死记硬背)来达到学习的目的,但效率低下。当然,也可以通过优秀的学习法来进行学习,比如今天讲的“费曼学习法”,可以将你的学习效率极大的提高。 费曼学习法是由加拿大物理学家费曼所发明的一种高效的学习方法,费曼本身是一个天才,13岁自学微积分,24岁加入曼...
学Linux到底学什么
来源:公众号【编程珠玑】 作者:守望先生 网站:https://www.yanbinghu.com/2019/09/25/14472.html 前言 ​我们常常听到很多人说要学学Linux或者被人告知说应该学学Linux,那么学Linux到底要学什么? 为什么要学Linux 在回答学什么之前,我们先看看为什么要学。首先我们需要认识到的是,很多服务器使用的是Linux系统,而作为服务器应...
深入理解C语言指针
一、指针的概念 要知道指针的概念,要先了解变量在内存中如何存储的。在存储时,内存被分为一块一块的。每一块都有一个特有的编号。而这个编号可以暂时理解为指针,就像酒店的门牌号一样。 1.1、变量和地址 先写一段简单的代码: void main(){ int x = 10, int y = 20; } 这段代码非常简单,就是两个变量的声明,分别赋值了 10、20。我们把内存当做一个酒店,而每个房间就...
相关热词 c#部门请假管理系统 c#服务器socket c# 默认的访问修饰符 c#拖动文件 c# 截取指定窗口屏幕 c# html对象传后台 c# 判断域名还是ip c#遮罩层 c# 取字符串中的数字 c# 网站高并发测试