JavaScript Thread.Sleep()

What is the JavaScript version of sleep()?

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: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 seconds later, showing sleep in a loop...'); // Sleep in loop
  for (let i = 0; i < 5; i++) { if (i === 3) await sleep(2000); console.log(i); } } demo();

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

Note that,java

  1. await can only be executed in functions prefixed with the async keyword, or at the top level of your script in some environments (e.g. the Chrome DevTools console, or Runkit).
  2. await only pauses the current async function

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

Compatibility

If for some weird reason you're using Node older than 7 (which has reached end of life), 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.jquery

 

What's the equivalent of Java's Thread.sleep() in JavaScript? [duplicate]

The simple answer is that there is no such function.git

The closest thing you have is:es6

var millisecondsToWait = 500; setTimeout(function() { // Whatever you want to do after the wait }, millisecondsToWait);

Note that you especially don't want to busy-wait (e.g. in a spin loop), since your browser is almost certainly executing your JavaScript in a single-threaded environment.github

Here are a couple of other SO questions that deal with threads in JavaScript:web

And this question may also be helpful:api

 

How to wait 5 seconds with jQuery?

Built in javascript setTimeout.promise

setTimeout( function() { //do something special }, 5000);

UPDATE: you want to wait since when the page has finished loading, so put that code inside your $(document).ready(...); script.

UPDATE 2: jquery 1.4.0 introduced the .delay method. Check it out. Note that .delay only works with the jQuery effects queues.

相關文章
相關標籤/搜索