JavaScript 的 sleep() 函数?
Sleep()
借助sleep(),我们可以创建一个函数来暂停执行一段固定时间。在像C和PHP这样的编程语言中,我们会调用sleep(sec)。Java 有thread.sleep(),Python 有time.sleep(),而Go有time.Sleep(2 * time.Second)。
JavaScript没有这些类型的休眠函数。但我们应该感谢 ES 2018 中的Promise和async/await 函数。因为这些特性帮助我们尽可能轻松地使用sleep()。让我们简单地讨论一下。
语法-1
sleep(Time in ms).then(() => { //// code })
我们可以像上面所示那样,使用带 then 回调的 sleep 函数。
语法-2
const work = async () => { await sleep(Time in ms) //code } work()
我们可以像上面所示那样,使用带 async/await 函数的sleep()函数。
示例
在下面的示例中,我们使用了带async/await 函数的sleep()。这里 sleep 函数与await一起使用以继续执行。最初,在async 函数“Hello Tutorix”开始时显示文本。稍后,使用sleep 函数暂停函数 3 秒。一旦时间段完成,则显示 sleep() 函数后面的文本(“Welcome to ........”)。它会重复直到循环终止,这意味着文本总共会重复 19 次,如输出所示。
<html> <body> <script> function sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } async function Tutor() { document.write('Hello Toturix'); for (let i = 1; i <20 ; i++) { await sleep(3000); document.write( i +" "+"Welcome to tutorix" + " " + "</br>"); } } Tutor() </script> </body> </html>
输出
Hello Tutorix // after 3 secs 1 Welcome to tutorix // after 3sec...and the text will repeat until the loop terminates for every 3 sec 2 Welcome to tutorix 3 Welcome to tutorix 4 Welcome to tutorix 5 Welcome to tutorix 6 Welcome to tutorix 7 Welcome to tutorix 8 Welcome to tutorix 9 Welcome to tutorix 10 Welcome to tutorix 11 Welcome to tutorix 12 Welcome to tutorix 13 Welcome to tutorix 14 Welcome to tutorix 15 Welcome to tutorix 16 Welcome to tutorix 17 Welcome to tutorix 18 Welcome to tutorix 19 Welcome to tutorix
广告
数据结构
网络
关系型数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP