Is it possible to trigger a reflow prior to initiating a lengthy JavaScript operation?

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?

Answer №1

To trigger a callback function:

$('#loadingDiv').display("fast", slowProcessFunction);

Once the div is displayed, your function will be executed.

Answer №2

If you're looking for a solution to handle asynchronous tasks in JavaScript, I recommend exploring jQuery's deferred functionality. Deferred objects are specifically designed for this purpose and you can learn how to use them by checking out a tutorial at this link.

I've also put together a simple example on JSFiddle to demonstrate how it works. Check out the fiddle here

Below is the JavaScript code snippet that showcases the implementation:

(function($) {
    function initLongWait() {
        var deferred = new $.Deferred();

        setTimeout(function() {
            deferred.resolve();
        }, 2000);

        return deferred.promise();
    }

    var promise = initLongWait();
    $('#wait').fadeIn();
    initLongWait().done(function() {
        $('#wait').fadeOut();
        $('#done').fadeIn();
    });
})(jQuery);

Answer №3

CodePen Example

The solution you implemented in #2 can be applied here as well.

$("#loadingDiv").show();
setTimeout(function(){
 runLengthyProcess();
 $("#loadingDiv").hide();
},10);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Refreshing a web page in Internet Explorer can cause the HTTP Header content to be altered

As I monitor my dashboard retrieving continuous data from an SAP server, I stumbled upon a solution to fetch the current server date. This approach allows me to display when the dashboard was last updated, and this date is displayed in the DOM. //Method f ...

What issues can be found in this piece of JQuery script?

<script src = "https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script> <script type="text/javascript"> //waiting for the document to be ready $(document).ready(function() { ...

Check if the user is null using React's useEffect hook and then perform a

I am currently working on implementing a protected route in Next JS. I have included a useEffect to redirect to the sign-in page if there is no user detected. const analytics = () => { const { userLoaded, user, signOut, session, userDetails, subscri ...

Is ColdFusion AJAX compatible with CF7 or only works on CF9?

Seeking assistance with a simple CFC that functions locally on CF9 but encounters issues on CF7, as it lacks the returnformat attribute in cffunction. How can I resolve this? I attempted to use SerializeJSON() on the returned struct without success. Any su ...

"Using jQuery to create a regex pattern for validating usernames

I need assistance creating a regex pattern for usernames that must follow the criteria below: Usernames can only include a-z, A-Z, 0-9 and - (hyphens); Usernames cannot be entirely composed of digits or hyphens but can contain characters; The first ...

What steps can be taken to resolve the error message "t.onSubmit is not a function" that occurs upon form submission?

Upon submitting a form, it should trigger the onSubmit method function. However, an error is being returned instead: TypeError: "t.onSubmit is not a function". I've attempted to address this issue by researching similar problems and solutions provide ...

Is it possible to position two fixed divs side by side?

I am currently in the process of building my online portfolio. I am looking to create two fixed divs that will not scroll, each occupying the full height of the page. The content between these two divs should be scrollable while the bars on the left and ri ...

Error in Angular Google Maps Component: Unable to access the 'nativeElement' property as it is undefined

I am currently working on creating an autofill input for AGM. Everything seems to be going smoothly, but I encountered an error when trying to integrate the component (app-agm-input) into my app.component.html: https://i.stack.imgur.com/mDtSA.png Here is ...

CSS gallery slideshow with images that smoothly fade-in and fade-out at a specified location

In the image below, at position 4 (marked by yellow circle) from the left where picture 6 is displayed, I want a cross-fade (fade-in/fade-out) gallery of images to take place. Specifically at position 4, I am looking for a cross-fade (fade-in/fade-out) ef ...

Customizing Material-UI styles using makeStyles

Currently, I am in the process of building a small portfolio website. Despite my attempts to style an avatar using the makeStyles class, it seems that the Mui avatar root is overriding my desired styling. I am wondering if there is a way to achieve this w ...

methods to retrieve value from a javascript function

Just a quick inquiry - what's the best way to pass or return a value from a function? Here is my code: function numberOfDivs(){ var numberOfElements = $("#div").children().length; // Counting the number of existing divs return numberOfElements; } ...

What do you do when you need to hide a table column that has a colspan

I have been searching for a solution to my unique table structure, but I haven't found any that match my situation. When attempting to hide column A or B, the following code works perfectly: $('table td:nth-child(1),table th:nth-child(1)') ...

Assertion error: 1 does not match the expected value of 6

I am faced with a challenging test that requires me to write code that will pass successfully. However, no matter what I try, all I get is the following error messages: "Failed asserting that 1 matches expected 6" when I return 6 and "Too few arguments t ...

How to generate a dropdown menu using a deeply nested JSON array

I'm looking to create a series of drop-down lists based on the JSON array provided below. There will be five drop-down lists, and when I select an option in one list, the other four should populate accordingly. For example, if I choose "Hindi" in the ...

Searching for a cake in CakePHP with autocomplete functionality

$( "#skills" ).autocomplete({source: function(request, response) { $.getJSON("http://server/current/indrealestates.com/properties/autosuggesthome/",{ term:request.term ,extraParams:$('#property_id').val()}, response ); }, ...

What are the steps for positioning material-ui icons to the right?

I have a list that is dynamically generated with the following code snippet: <list className = "todos-list"> {allTodos.map((todo, index)=> { return ( ...

Creating a dropdown menu for an extensive list of 100 menu items: a step-by-step guide

In my React JS front-end project, I have implemented a drop-down menu using Material-UI. Currently, the menu items are hardcoded which works fine for a small number of items. However, this approach becomes cumbersome when dealing with a larger number of ...

Error encountered: Mocha - The property '$scope' cannot be read as it is undefined

I encountered an issue: Error: Type Error - Cannot read property '$scope' of undefined at $controller (angular/angular.js:10327:28) at angular-mocks/angular-mocks.js:2221:12 at Context. (src/client/app/peer-review/post-visit.co ...

Is there a way to implement a watch on $validator.errors in Vue.js using the Vee Validation plugin?

My intention was to implement a watch on $validator.errors, so that any error that arises gets logged, To achieve this, I checked the length of errors and stored self.errors.all() in a variable, However, I'm curious if it's possible to directly ...

Encountering the AngularJS .Net Core routing $injector:modulerr error

I'm currently learning about .Net Core and AngularJS by following tutorials. However, I've encountered an error while attempting to implement client routing in the newest version of .Net Core with default configuration. The AngularJS error I rece ...