w3resource

Simulate a Loading Spinner for Async Operations in JavaScript


Simulating a Loading Spinner:

Write a JavaScript program that displays a "loading" message while waiting for an async operation to complete.

Solution-1:

Code:

// Function to simulate an async operation with a delay
function asyncOperation() {
  return new Promise((resolve) => {
    setTimeout(() => resolve('Async operation completed!'), 3000); // Resolves after 3 seconds
  });
}

// Function to simulate a loading spinner
async function simulateLoadingSpinner() {
  console.log('Loading...'); // Display loading message
  const result = await asyncOperation(); // Wait for async operation to complete
  console.log(result); // Display the result after completion
}

simulateLoadingSpinner();

Output:

"Loading..."
"Async operation completed!".

Explanation:

  • 'asyncOperation' simulates a delayed async operation using 'setTimeout'.
  • 'simulateLoadingSpinner' logs a "Loading..." message before awaiting the async operation.
  • Once the operation completes, the resolved value is logged.

See the Pen promises-and-async-await-exercise-17 by w3resource (@w3resource) on CodePen.


Improve this sample solution and post your code through Disqus

Previous: Resolving Nested Promises in JavaScript with Async/Await.
Next: Cancelable Promises in JavaScript with Practical Examples.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.