JavaScript 的 sleep() 函式?


Sleep()

藉助sleep(),我們可以建立一個函式來暫停執行一段固定時間。在像CPHP這樣的程式語言中,我們會呼叫sleep(sec)。Java 有thread.sleep(),Python 有time.sleep(),而Gotime.Sleep(2 * time.Second)

JavaScript沒有這些型別的休眠函式。但我們應該感謝 ES 2018 中的Promiseasync/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

更新於:2023年9月2日

51K+ 瀏覽量

啟動您的職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.