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,
awaitcan only be executed in functions prefixed with theasynckeyword, or at the top level of your script in some environments (e.g. the Chrome DevTools console, or Runkit).awaitonly pauses the currentasyncfunction
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/awaitfeature 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/awaitlanded 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 ...
随机推荐
- 干货分享!Oracle 的入门到精通 ~
Oracle Database,又名Oracle RDBMS,或简称Oracle.是甲骨文公司的一款关系数据库管理系统.它是在数据库领域一直处于领先地位的产品.可以说Oracle数据库系统是目前世界上 ...
- Python爬虫之简单爬虫框架实现
简单爬虫框架实现 目录 框架流程 调度器url管理器 网页下载器 网页解析器 数据处理器 具体演示效果 框架流程 调度器 #导入模块 import Url_Manager import parser_ ...
- Linux下make cmake 编译等啥意思?
写程序大体步骤为: 1.用编辑器编写源代码,如.c文件. 2.用编译器编译代码生成目标文件,如.o. 3.用链接器连接目标代码生成可执行文件,如.exe. 但如果源文件太多,一个一个编译时就会特别麻烦 ...
- 关于IDEA的application.properties读取乱码,以及显示乱码问题
设置编码 如果设置之后还是不成功,就重启IDEA 再不行就删除application.properties重新编辑, 我采用的是注释掉要读取的中文部分,再下面再写一行
- 15、Nginx动静分离实战
1.Nginx动静分离基本概述 动静分离, 通过中间件将动静分离和静态请求进行分离. 那为什么要通过中间件将动态请求和静态请求进行分离? 减少不必要的请求消耗, 同时能减少请求的延时. 通过中间件将动 ...
- emwin之窗口ID的唯一性
@2019-04-30 [小记] emwin窗口ID是唯一的 emwin多次创建同一窗口,则窗口句柄不同,多次删除窗口采取LIFO机制,即最新创建的窗口被首先删除 获取多次创建同一窗口的ID,准确位置 ...
- zabbix 启到不起来:active check configuration update from [127.0.0.1:10051] started to fail (cannot connect to [[127.0.0.1]:10051]: [111] Connection refused)
cat /var/log/zabbix_agent_log 查看日记出现报错:active check configuration update from [127.0.0.1:10051] star ...
- 面试复习题(一)Java系列
(根据自己的理解和根据黑马资料总结—意见不统一我会写上自己的理解) 一.Java面向对象 1.面向对象都有哪些特性以及你对这些特性的理解 继承.封装.多态.(抽象) 2.public,private, ...
- 标准C语言(4)
分支语句可以在程序执行的时候从几组语句里选择一组,执行而忽略其他组,在编写程序的时候如果遇到多种可能性,每种可能性需要专门的语句处理,这种情况下就可以考虑采用分支结构解决问题 if关键字可以用来编写分 ...
- 【AGC005 F】Many Easy Problems
神他吗一天考一道码农题两道 FFT(其实还是我推式子一窍不通) 题意 给你一棵 \(n\) 个点的树,再给你一个常数 \(k\). 设 \(S\) 为树上某些点的集合,定义 \(f(S)\) 为最小的 ...