How I Delayed the Loading Indicator in my Web App for a Better User Experience
For my web app, I wanted to have a loading indicator after the user performed an action. Specifically, for making an Ajax call after hitting a “Save” button.
This is specifically useful for people on a slow mobile connection.
The problem is that if a user has a fast internet connection, the loading indicator will appear and then quickly disappear; as if it’s flashing by.
The solution is to detect when the user pressed a button, and only display the loading indicator after 2 seconds.
If the Ajax call already completed (in less than 2 seconds), the loading indicator won’t even appear.
More Requirements
I wanted to pass in a specific container in the DOM to show/hide.
I wanted the solution to be generic, so I included a “helper” function to dynamically target elements.
The Solution
Code Explanation
- loadingSpinnerHTML is my HTML/CSS based loading indicator. I’m using Bootstrap, so you’ll need that CSS.
- hideLoader() clears a previously set timeout. It’ll find a specific element (the selector), and “clear” it.
- saleAddUpdate() is the function that makes the Ajax call. On success it’ll hide the loading indicator if it appeared. The part at the end (setting loadingTimeout() is what makes it appear, but only if 2 seconds have gone by.