Search code examples
javascriptfreezeanimated-gif

How can I continue to play my GIF during JavaScript processing (as it freezes)?


My GIF image freezes after 5 seconds while my JavaScript code is doing some work. It unfreezes when procesing is finished.

Is there a solution to animate my GIF while the code is executing?

Here's my JavaScript code:

var play = function() {
    var image = document.getElementById('img');
    image.style.display="block";

    window.setTimeout(function(){
        for ( var i =0; i < 2000000000; i++ )
        {
            //Do nothing, in example
        }
    }, 5000);
};

var stop = function() {
    var image = document.getElementById('img');
    image.style.display="none";
};

HTML code:

<img id="img" src="loader.gif" style="display: none;"/>
<button id="Start" onclick="play()">Play</button>
<button id="Stop" onclick="stop()">Stop</button>

Solution

  • I think that in this case you should use webworker elements. They allow you to do some asynchronous operation in the background of the UI elements.

    One example

    <p>Value passed by the worker: <output id="result"></output></p>
    <script>
        var worker = new Worker('worker.js');
    
        worker.onmessage = function (event) {
            document.getElementById('result').textContent = event.data;
        };
    </script>
    

    In a separate file (worker.js):

    var n = 1;
    search: while (true) {
        n += 1;
    
        for (var i = 2; i <= Math.sqrt(n); i += 1)
            if (n % i == 0)
                continue search;
    
        // Found a prime!
        postMessage(n);
    }
    

    Every time that you call postMessage you send some data from the background (that fires onmessage event of the worker element ) to the main thread.

    Have a look at Using jQuery UI progress bar with MVVM, Knockout and web workers for your case:

    In this post I would like to explore:

    • How to use the jQuery UI progress bar with KnockoutJS and MVVM pattern, as a simple example of reusing existing JavaScript UI components.
    • How to use web workers to execute long running task asynchronously and notify view model about the results and progress.