Imagine you have this endpoint, which artificially sleeps for 3 seconds before sending back a response:
service.get('/wait', (request, response) => {
setTimeout(() => {
response.json({
ok: true,
results: "Thanks for waiting.",
});
}, 3000);
});
You are unlikely to write an endpoint that delays its response artificially. However, your service might need to read in a file, access a database, or perform an expensive computation that will trigger a similar delay.
Try adding this endpoint to your service, restarting it, and accessing the endpoint via your browser or curl
. Do you experience the delay?
Suppose that you accessed this endpoint when a viewer clicked on a button:
Try clicking the button. Do you see the message appear? This page does not provide a good user experience. It offers no confirmation that the click actually happened or that a fetch is running in the background. The viewer is likely to click the button multiple times and grow frustrated.
You decide to give the user feedback that the page is working on its task by displaying a progress indicator right in the middle of the page. You choose to make a progress wheel using a div
with a rounded border. You give it a fixed position in the center of the page and set it spinning use a keyframe animation:
But you don't want it animating right away. You hide it initially by setting its display
property to none
. When the click happens, you set display
to block
. When the fetch finishes, you hide it again:
Try clicking the button. Does the wheel appear and disappear?
Real delays are caused by constrained resources. Therefore, you want to prevent the user from clicking the fetch button until the response to the original click has been received. You disable the button after it's clicked and reenable it once the fetch has completed:
Try clicking the button. Does the button become unclickable?
Disabling the button is only a minor safeguard against spamming the button. A determined user could open up the developer tools and re-enable it.