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

Can someone please explain how to prevent Prettier from automatically inserting a new line at the end of my JavaScript file in VS Code?

After installing Prettier and configuring it to format on save, I encountered an issue while running Firebase deploy: 172:6 error Newline not allowed at end of file eol-last I noticed that Prettier is adding a new line at the end when formatting ...

Encountered an issue during the installation of react router - in need of assistance to resolve the error

Encountering an Error Error Message when Installing React Router DOM: npm WARN: The use of global `--global` and `--local` is deprecated. Use `--location=global` instead. npm ERR! code EPERM npm ERR! syscall mkdir npm ERR! path D:\ npm ERR! errno -404 ...

Tips for creating a drawing grid with a table

I am currently working on a project where I need to create a canvas-like table with around 10,000 cells. The goal is to allow users to draw on this canvas by moving their mouse over it while holding down specific keys (e.g. ctrl for blue, shift for red). ...

Unable to fetch the AJAX request data value within the Django view function

Currently, I am facing an issue with an AJAX request in Django3 and Python 3.8. When I try to print the data received from the POST model using request.GET.get in the console, it returns "None". Surprisingly, when I alert the passed data in JavaScript, I g ...

Using (javascript:) within Href attributes

Recently, I've noticed some people including "javascript:" in the href attribute of an a tag. My question is: what is the purpose of this? Does it guarantee that clicking on the a tag directs the function of the click to JavaScript for handling, rathe ...

Send data in JSON format from an AngularJS client to an Express server

Having an issue when trying to send a JSON Object from an AngularJS $http service to an Express Server. The server receives an empty object: "{}" I've looked at this topic, but it hasn't resolved my problem: angular post json to express This is ...

Implementation issue with Hashids library in Vue.js causing functionality hiccups

I'm having trouble getting the library hashids to cooperate with vue.js The method I would like to use is: <template> <div class="container"> {{ hashids.encode('1') }} </div> </template> <script& ...

Ensure that the page has completely loaded using WebdriverJS

Is there a reliable method to ensure that a page has fully loaded using selenium-webdriver in JavaScript? I came across this similar query, but I require an implementation specifically in JavaScript. var webdriver = require('selenium-webdriver') ...

Shut down jquery modal

I have successfully imported Jquery Modal using the following two links (js and css) <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-modal/0.9.1/jquery.modal.min.js"></script> <link rel="stylesheet" href="https://cdnjs.cl ...

The overflow:hidden property does not seem to be effective for controlling the display of the

I'm attempting to construct a carousel using a ul element where the li items act as blocks within the ul container. However, I have encountered difficulties with two different approaches where the overflow property does not behave as expected. Approa ...

When attempting to retrieve a data object using a Vuex action, I encounter an "Uncaught (in promise) TypeError" when trying to access the data within the object

Recently, I've been diving into Vuex and its actions for fetching data. While everything seems to be working smoothly - accessing the films object, selecting films from it - I encounter an error when trying to access specific data within a film. Vuex ...

Struggling to successfully submit data from an API to the project's endpoint, encountering Error 405 method rejection

I'm working on integrating data from the openweathermap API into my project's endpoint to update the User interface. Everything seems to be functioning correctly, except for when I attempt to post the data to the endpoint. What am I overlooking h ...

The integration of express and cors() is malfunctioning

Currently, I am developing a React application and facing an issue while trying to make an API call to https://itunes.apple.com/search?term=jack+johnson In my project, there is a helper file named requestHelper.js with the following content : import &apo ...

Is it possible to incorporate Nth child into JavaScript?

Is it feasible to implement an Nth Child in the following code snippet? $(function() { var count = $(".parent a").length; $(".parent div").width(function(){ return ($(".parent").width()/count)-5; }).css("margin-right","5px"); }); ...

The Vue property or method is unrecognized when utilizing the non-minified version

When I attempted to display the name 'John' using an inline template in a simple Vue example, I encountered the following error message: [Vue warn]: Property or method "name" is not defined on the instance but referenced during render. ...

PhantomJS Karma encountering SyntaxError when trying to export variables

I've encountered an issue while running Karma and PhantomJS. When I attempt to run, the console displays the following message: 22 03 2016 14:58:47.865:WARN [karma]: No captured browser, open http://localhost:9876/ 22 03 2016 14:58:47.875:INFO [karm ...

The owl carousel is able to smoothly transition even when there is only one slide present in the carousel

Seeking assistance here. I am currently utilizing a carousel within a CMS and would like to provide the option for customers to display only one slide if they choose. However, when only one slide is present, the fade transition still occurs, resulting in ...

Ways to determine the height of a responsive div's background image

I have a container with a background image. Inside this container, there are additional elements like my navigation bar. My goal is to make the container have the same height as the background image. I've attempted the following: .bg { ...

Tips for selecting a specific item in a list using onClick while iterating through a JSON array in React

I have a unique JSON file filled with an array of objects, each containing a "Question" and "Answer" pair (I am working on creating an FAQ section). My current task involves mapping through this array to display the list of questions, a process that is fun ...

Using node.js to parse an XML file from a URL and iterate through it to retrieve all the URLs contained within

I am currently utilizing the node module xml2js. The format of my xml file looks like this: <?xml version="1.0" encoding="UTF-8" ?> <?xml-stylesheet type="text/xsl"?> <?xml-stylesheet type="text/css" media="screen" href="some url" ?> ...