Sleep()
Sleep() की मदद से हम किसी फंक्शन को निश्चित समय के लिए रोक सकते हैं। C और PHP जैसी प्रोग्रामिंग भाषाओं में हम sleep(sec) कॉल करेंगे। जावा में thread.sleep(), पायथन में time.sleep() और GO में time.Sleep(2 * time.Second) होता है।
जावास्क्रिप्ट में इस तरह के स्लीप फंक्शन्स नहीं होते। लेकिन हमें प्रॉमिसेस और ES 2018 में async/await फंक्शन का धन्यवाद करना चाहिए। क्योंकि इन फीचर्स ने sleep() का उपयोग करना उतना ही आसान बना दिया है। आइए इसे संक्षेप में समझते हैं।
सिंटैक्स-1
sleep(Time in ms).then(() => { //// code })
हम स्लीप फंक्शन को then कॉलबैक के साथ उपयोग कर सकते हैं जैसा कि ऊपर दिखाया गया है।
सिंटैक्स-2
const work = async () => { await sleep(Time in ms) //code } work()
हम स्लीप फंक्शन को async/await फंक्शन के साथ उपयोग कर सकते हैं जैसा कि ऊपर दिखाया गया है।
उदाहरण
निम्नलिखित उदाहरण में, हमने स्लीप() का उपयोग async/await फंक्शन के साथ किया है। यहां स्लीप फंक्शन await के साथ जारी रखने के लिए है। प्रारंभ में async फंक्शन में टेक्स्ट "Hello Tutorix" फंक्शन शुरू होने पर प्रदर्शित होता है। बाद में, फंक्शन को स्लीप फंक्शन का उपयोग करके 3 सेकंड के लिए रोका जाता है। एक बार समय अवधि पूरी हो जाने पर, स्लीप फंक्शन के बाद का टेक्स्ट ("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