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:
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,
await
can only be executed in functions prefixed with theasync
keyword, or at the top level of your script in some environments (e.g. the Chrome DevTools console, or Runkit).await
only pauses the currentasync
function
Two new JavaScript features helped write this "sleep" function:
- Promises, a native feature of ES2015 (aka ES6). We also use arrow functions in the definition of the sleep function.
- The
async/await
feature lets the code explicitly wait for a promise to settle (resolve or reject).
Compatibility
- promises are supported in Node v0.12+ and widely supported in browsers, except IE
async
/await
landed in V8 and has been enabled by default since Chrome 55 (released in Dec 2016)- it landed in Node 7 in October 2016
- and also landed in Firefox Nightly in November 2016
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()的更多相关文章
- How does a single thread handle asynchronous code in JavaScript?
原文:https://www.quora.com/How-does-a-single-thread-handle-asynchronous-code-in-JavaScript ----------- ...
- 探索Javascript异步编程
异步编程带来的问题在客户端Javascript中并不明显,但随着服务器端Javascript越来越广的被使用,大量的异步IO操作使得该问题变得明显.许多不同的方法都可以解决这个问题,本文讨论了一些方法 ...
- Javascript modules--js 模块化
https://medium.freecodecamp.org/javascript-modules-a-beginner-s-guide-783f7d7a5fcc 这个网站也是非常好:https:/ ...
- Node.js 异步异闻录
本文首发在个人博客:http://muyunyun.cn/posts/7b9fdc87/ 提到 Node.js, 我们脑海就会浮现异步.非阻塞.单线程等关键词,进一步我们还会想到 buffer.模块机 ...
- React Native桥接器初探
本文假设你已经有一定的React Native基础,并且想要了解React Native的JS和原生代码之间是如何交互的. React Native的工作线程 shadow queue:布局在这个线程 ...
- 深入理解react-native
欢迎转载,请支持原创,保留原文链接:http://blog.ilibrary.me http://blog.ilibrary.me/2016/12/25/react-native-internal ( ...
- JavaScript 编写多线程代码引用Concurrent.Thread.js(转)
这是一个很简单的功能实现: <script type="text/javascript" src="Concurrent.Thread.js">&l ...
- JavaScript 编写线程代码引用Concurrent.Thread.js
马上来下载和使用源码吧!假定你已经将下载的源码保存到一个名为Concurrent.Thread.js的文件夹里,在进行任何操作之前,先运行如下程序,这是一个很简单的功能实现: <script t ...
- 【转】《高级前端3.6》JavaScript多线程——Concurrent.Thread.js, WebWork
原文链接:http://www.cnblogs.com/woodk/articles/5199536.html JavaScript多线程,在HTML5 WebWork没出现之前很多人都是用Concu ...
随机推荐
- Linux小知识:rm -rf/*会将系统全部删除吗
Linux小知识:rm -rf/*会将系统全部删除吗 本文是学习笔记,视频地址为:https://www.bilibili.com/video/av62839850 执行上面的命令并不会删除所有内容( ...
- JAVA网络编程入门
JAVA网络编程入门 软件结构 C/S结构 B/S结构 无论哪一种结构,都离不开网络的支持.网络编程,就是在网络的条件下实现机器间的通信的过程 网络通信协议 网络通信协议:通信双方必须同时遵守才能完成 ...
- java 矩阵的运算
首先需要引入包Jama-1.0.2.jar 这个包下封装的对矩阵运算的方法,包括矩阵的加减乘除逆运算等 包下载地址:https://math.nist.gov/javanumerics/jama/ ...
- js 禁用F12 和右键查看源码
<script> window.onkeydown = function(e) { if (e.keyCode === 123) { e.preventDefault() } } wind ...
- 将数据导出到 excel ,然后下载下来
private static final String SHEET_NAME = "培养计划表"; /** * @param response * @param trainingN ...
- no input file specified 三种解决方法
一.IIS Noinput file specified 方法一:改PHP.ini中的doc_root行,打开ini文件注释掉此行,然后重启IIS 方法二: 请修改php.ini 找到 ; cgi.f ...
- stm32 development
1.www.st.com st官网 2.www.stmcu.com.cn st中文网 3.www.stmcu.org.cn st中文社区
- 浙大数据结构课后习题 练习二 7-2 Reversing Linked List (25 分)
Given a constant K and a singly linked list L, you are supposed to reverse the links of every K elem ...
- 从头开始 — CSS — 垂直居中
事实上,每次面试前端必问的问题就是这个.及其常见的需求,看起来似乎非常简单,但是实现起来很费劲,尤其是涉及尺寸不固定的元素. 本篇文章将介绍比较流行的几种方法. 行内块 <body> &l ...
- jdk1.8环境变量配置
JAVA_HOME=/usr/java/jdk1.8.0_45PATH=$JAVA_HOME/bin:$PATHCLASSPATH=.:$JAVA_HOME/jre/lib/ext:$JAVA_HOM ...