How to add a loading spinner to your async functions in javascript

Adel Benyahia

--

In modern web development you have for sure used async/await in javascript

An async function is a function declared with the async keyword, and the await keyword is permitted within it. The async and await keywords enable asynchronous, promise-based behavior to be written in a cleaner style, avoiding the need to explicitly configure promise chains.

But for a heavy function that do a lot of calculation, or when using feth api with a slow internet connection, this process can run for a long period of time and your application ui appears as hanging for the end users, most users will get bored or even worse close your application or uninstall it.

One of the fundamental principles of User Experience (UX) is that a visitor expects to see some feedback when they do an actionable work on a website or an app. For example.

You don’t want that to happen, we will solve that by using “Loaders”. This animation lets the user know that their request has been received and your application is loading the data.

For that we need three files

index.html

This file contain 3 buttons

1- button (1) to load data with loading spinner animation

2- button (2) to load data with out the loading spinner animation

3- button(3) to clear the showed data.

and one <p> to show the loaded data

very basic UI

style.css

with contain the css for the loader, with two important css class:

1- “center” to show the loading spinner centred

2- “loader-hide” to hide loader

app.js

that contain a basic async fetch function from dymmyjson.com

with two functions getData() and cleanData()

The complet app in Github

….

Extra resources

You can change the loading spinner animation by visiting one of these cool free websites

--

--

Adel Benyahia

Web application developer (HTML │ CSS │ JS | ReactJS | NextJS | NestJS | MERN)