0

I use Ajax load icons all the time for when I do ajax requests.

I want to know if it's possible to accomplish the same thing with just regular javascript code. For example:

$('button').on('click', function(){
    showLoadingBar();
    longProcess();
    hideLoadingBar();
});

longProcess() is just a function that can take 1-3 seconds to process (it does a lot of calculations and manipulates the DOM but doesn't do any ajax requests).

Right now, the browser halts/freezes during these 1-3 seconds, so what I would rather do is show a loading icon during this time. Is this possible? The code I have above pretty much ignores showLoadingBar().

Justin
  • 623
  • 1
  • 10
  • 24
  • 2
    That is because your functions are synchronous.. It waits for the current function to be completed until it hits the next one – Sushanth -- Nov 05 '12 at 21:01
  • You shouldn't have a 1 to 3 second function at all, the maximum should be 200ms before a page feels unresponsive. Have a look at http://stackoverflow.com/q/10180391/1048572, http://stackoverflow.com/q/4288759/1048572 and linked (related) questions – Bergi Nov 05 '12 at 21:54

3 Answers3

4

The DOM won't be updated until the current Javascript process ends, so you can't do it just like that. You can however use setTimeout to get around that:

showLoadingBar();
setTimeout(function() {longProcess(); hideLoadingBar(); }, 1);

What happens above, in case it isn't clear, is that showLoadingBar is executed, then a timeout is set up. The current process will then end and allow the DOM to update with the loading bar, before the timeout is invoked, very shortly after. The handler executes your heavy function and when it's done, hides the loading bar again.

troelskn
  • 115,121
  • 27
  • 131
  • 155
  • I have used setTimeout before, but I never realized that it would cause the current process to end and update the DOM. This is exactly what I need, thanks. – Justin Nov 05 '12 at 21:17
1

The following will give you control over the action on click. What this means is you can disable the clicking ability till it has finished running. But also i've including setTimeout which returns control to the browser (thus removing that annoying "lockup" feeling) and in the timeout function we preform our long process then re-enable the button! VIOLA!

function startProc() {
    var $this = $(this);
    $this.off("click", startProc);
    showLoadingBar();
    setTimeout(function() {
        longProcess();
        hideLoadingBar();
        $('button').on('click', startProc);
    });
}

$('button').on('click', startProc);
SpYk3HH
  • 22,272
  • 11
  • 70
  • 81
  • This is something I will use since I've always wanted to disable clicking the button while something is happening. Thanks for this idea. – Justin Nov 05 '12 at 21:18
-3

Dude,

Use the .bind method, which in this case is performed so:

$('button').bind('click', function(){
    showLoadingBar();
    longProcess();
    hideLoadingBar();
});