+ 2

How to implement a loader or progress bar while function is executed?

I have a function that needs to process first before user can actually submit the form. This function triggered when a textbox value has been changed. I'm planning to add a loader after the textbox value has been changed and it will be an indication that the user must wait.

26th Oct 2020, 12:07 PM
Ynelle Kyle Novicio
Ynelle Kyle Novicio - avatar
1 ответ
+ 3
It sounds like you have some work that'll take at least a few seconds to complete. Make sure this function won't lock up/freeze your browser tab. If this function is executing in the browser, you'll need to change it into something asynchronous to give the browser time to respond to user input and not lock up. Web browsers don't let the main thread continue running for more than a few seconds without asking the user to confirm continuing your "unresponsive" script. You could do this with a service worker if you're using HTTPS with a proper certificate. Another way to break up the work, is to write your function like this: function doLotsOfWork(inputs) { var someResults = []; // declare whatever information you want to build. return new Promise(function(resolver, rejecter) { // Adjust doALittleWork to take no more than 50ms or so. // This way, the user probably won't notice any responsiveness issues. function doALittleWork() { // FIXME: process some more inputs and put the new results in results. // update progress element's value. if (there is still more work to do) { setTimeout(doALittleWork, 0); // give other JavaScript a chance to run and // then call doALittleWork as soon after that's complete. } else { resolver(results); } } doALittleWork(); // get the asynchronous loop started. }); } I added a more complete implementation and demo of this at: https://code.sololearn.com/WAu6ci62d0L0/ I used this technique in a few codes that can take several seconds to draw high quality downloaded images. For example, the download button on the right side of: https://code.sololearn.com/W6e6xWN0T7Jv/ - Also another download button on the right of: https://code.sololearn.com/WVhoMHzy3K81/
29th Oct 2020, 5:13 AM
Josh Greig
Josh Greig - avatar