JavaScript Sleep() 函数?

front end technologyjavascriptobject oriented programming

Sleep()

借助 sleep(),我们可以创建一个函数来暂停执行一段固定的时间。在 C 和 PHP 等编程语言中,我们会调用 sleep(sec)。 Java 有 thread.sleep(),Python 有 time.sleep(),Go time.Sleep(2 * time.Second)

JavaScript 没有这些 sleep 函数。但我们应该感谢 ES 2018 中的 promises async/await 函数。因为这些功能帮助我们尽可能轻松地使用 sleep() 。让我们简单讨论一下。

syntax-1

sleep(Time in ms).then(() => {
//// code
})

我们可以使用 sleep 函数并回调,如上所示。

语法-2

const work = async () => {
await sleep(Time in ms)
//code
}
work()

我们可以将 sleep() 函数与 async/await 函数结合使用,如上所示。

示例

在下面的示例中,我们将  sleep()async/await 函数 结合使用。此处 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

相关文章