Ready to face the criticism, I understand that this question has been asked many times before, and I am aware that there are likely more efficient ways to achieve what I'm trying to do...
In a JavaScript function, I have a process that can take up to 10 seconds to complete. I also have a "loading div" that I can display and hide whenever needed. Normally, the show/hide operation happens quickly, but if I try to do it in the same call chain as my long-running function, the browser doesn't have time to refresh and display the loading div before being locked up by the lengthy task.
I've attempted different approaches:
1 - simply showing the div and then calling the function:
$('#loadingDiv').show();
longRunningFunction();
2 - displaying the div and then calling the long running function within a setTimeout to run after the current function finishes:
$('#loadingDiv').show();
setTimeout(function(){longRunningFunction();}, 0);
3 - similar to 2 but with a longer timeout:
$('#loadingDiv').show();
setTimeout(function(){longRunningFunction();}, 100);
By using an even longer timeout (e.g., 5000 milliseconds), I managed to get the loading screen to display and the long running function to execute properly. However, this approach adds to the execution time and may not be compatible across all browsers (it just happened to work on the browser I was using at the time - another browser might not behave the same way).
I've tried various techniques found on SO and other sources involving altering offsetLeft
/ offsetTop
of page elements, manipulating self.status
, but everything I attempt seems to result in the same outcome: the browser freezes for a few moments, displays old content, and then shows the loading div once the long-running function is done.
I understand that what I'm doing may not be best practice, but it's what I need for now. In the future, I plan to:
1) Break down the code into smaller segments
2) Potentially move it to a Web Worker
3) Optimize it so it's faster and doesn't freeze the browser
But, for now, does anyone have a simple solution to ensure that the "loading div" is shown to the user before the long-running operation begins?