
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
How to implement asynchronous loop in JavaScript?
Following is the code to implement asynchronous loop in JavaScript −
Example
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } .result { font-size: 20px; font-weight: 500; color: blueviolet; } </style> </head> <body> <h1>Asynchronous loop in JavaScript</h1> <div class="result"></div> <button class="Btn">CLICK HERE</button> <h3>Click on the above button to start our asynchronous loop</h3> <script> let resEle = document.querySelector(".result"); async function waitTime(time) { return new Promise((resolve) => { setTimeout(resolve, time); }); } async function someFunction() { for (let i = 0; i < 10; i++) { await waitTime(2000); resEle.innerHTML += "i = " + i + "<br>"; } } document.querySelector(".Btn").addEventListener("click", () => { someFunction(); }); </script> </body> </html>
Output
On clicking the ‘CLICK HERE’ button the loop will print 1 to 10 −
- Related Articles
- Asynchronous Functions and the Node Event Loop in Javascript
- How to chain asynchronous functions in JavaScript?
- How does asynchronous code work in JavaScript?
- How to implement WHILE LOOP with IF STATEMENT MySQL?
- How to return the response from an asynchronous call in Javascript?
- How to break a loop in JavaScript?
- How to implement Polymorphism in JavaScript?
- Explain Asynchronous vs Deferred JavaScript
- How to use nested while loop in JavaScript?
- How to use nested for loop in JavaScript?
- How to implement basic Animation in JavaScript?
- How to implement quick sort in JavaScript?
- How to implement insertion sort in JavaScript?
- How to implement merge sort in JavaScript?
- How to add delay in a loop in JavaScript?

Advertisements