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:

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,

  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:

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.

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

The simple answer is that there is no such function.

The closest thing you have is:

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.

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

And this question may also be helpful:

How to wait 5 seconds with jQuery?

Built in javascript setTimeout.

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.

JavaScript Thread.Sleep()的更多相关文章

  1. How does a single thread handle asynchronous code in JavaScript?

    原文:https://www.quora.com/How-does-a-single-thread-handle-asynchronous-code-in-JavaScript ----------- ...

  2. 探索Javascript异步编程

    异步编程带来的问题在客户端Javascript中并不明显,但随着服务器端Javascript越来越广的被使用,大量的异步IO操作使得该问题变得明显.许多不同的方法都可以解决这个问题,本文讨论了一些方法 ...

  3. Javascript modules--js 模块化

    https://medium.freecodecamp.org/javascript-modules-a-beginner-s-guide-783f7d7a5fcc 这个网站也是非常好:https:/ ...

  4. Node.js 异步异闻录

    本文首发在个人博客:http://muyunyun.cn/posts/7b9fdc87/ 提到 Node.js, 我们脑海就会浮现异步.非阻塞.单线程等关键词,进一步我们还会想到 buffer.模块机 ...

  5. React Native桥接器初探

    本文假设你已经有一定的React Native基础,并且想要了解React Native的JS和原生代码之间是如何交互的. React Native的工作线程 shadow queue:布局在这个线程 ...

  6. 深入理解react-native

    欢迎转载,请支持原创,保留原文链接:http://blog.ilibrary.me http://blog.ilibrary.me/2016/12/25/react-native-internal ( ...

  7. JavaScript 编写多线程代码引用Concurrent.Thread.js(转)

    这是一个很简单的功能实现: <script type="text/javascript" src="Concurrent.Thread.js">&l ...

  8. JavaScript 编写线程代码引用Concurrent.Thread.js

    马上来下载和使用源码吧!假定你已经将下载的源码保存到一个名为Concurrent.Thread.js的文件夹里,在进行任何操作之前,先运行如下程序,这是一个很简单的功能实现: <script t ...

  9. 【转】《高级前端3.6》JavaScript多线程——Concurrent.Thread.js, WebWork

    原文链接:http://www.cnblogs.com/woodk/articles/5199536.html JavaScript多线程,在HTML5 WebWork没出现之前很多人都是用Concu ...

随机推荐

  1. $store.getters调用不执行

    $store.getters调用不执行 api:https://vuex.vuejs.org/zh/guide/getters.html 场景: 在登录时将登录得到的用户信息存储在vuex的state ...

  2. 本人亲测-inno setup打包EXE(较完整实例)

    ; Script generated by the Inno Setup Script Wizard.; SEE THE DOCUMENTATION FOR DETAILS ON CREATING I ...

  3. js 获取当前月份 第一天和最后一天

    js 获取当前月份 第一天和最后一天 var now = new Date(); //当前日期 var nowMonth = now.getMonth(); //当前月 var nowYear = n ...

  4. vs编译项目报错:The OutputPath property is not set for this project

    今天使用VS2008编译项目时报错: The OutputPath property is not set for this project.  Please check to make sure t ...

  5. Ubuntu18.10中pip install mysqlclient 出现EnvironmentError: mysql_config not found错误

    Complete output from command python setup.py egg_info: sh: 1: mysql_config: not found Traceback (mos ...

  6. P1:天文数据获取

    Step1:在sloan的casjob里http://casjobs.sdss.org/CasJobs/,密码用户 jiangbin  123456 查询满足条件的光谱对象,得到光谱对象的plate, ...

  7. 关于hdfs的一些认知

    先从网上copy一些优势点 1.高容错性数据自动保存多个副本.它通过增加副本的形式,提高容错性.某一个副本丢失以后,它可以自动恢复,这是由 HDFS 内部机制实现的,我们不必关心. 2.适合批处理它是 ...

  8. wampserver You don't have permission to access / on this server. 解决方法

    最近在安装最近版wampserver 2.2 d时发现安装好后启动服务器,访问localhost显示You don't have permission to access / on this serv ...

  9. 2019/9/18 IIS服务器 ftp站安装:隔离模式

    net user ftp1  /add 添加两个账户 在d盘下创建ftp站的文件夹ftptest,进入文件夹,创建文件夹LocalUser,进入LocalUser 分别创建administrator ...

  10. python-迭代器与生成器2

    python-迭代器与生成器2 def fib(max): n,a,b=0,0,1 while n<max: #print(b) yield b a,b=b,a+b #t=(b,a+b) 是一个 ...