0

I've noticed that in certain situations, a spinner won't show up till later than I want, if ever. I've tried a few different set-ups, with similar results, including using spin.js.

For example if I have this HTML:

<div id="spinner" style="display:none"><img src="spinner.gif" /></div>
<textarea id="myInput"></textarea>

Javascript:

var validate = function() {
    $('#spinner').show();
    var val = $('#myInput').val();
    var result = doSomethingModeratelyComplexWith(val);
    $('#spinner').hide();
    return result;
}

If the amount of data in the textarea is above a certain threshold, the spinner doesn't show. In the past I've sometimes dealt with this by using a timeout of 50-100ms around the "heavy" code, but A) I never liked that solution and B) it makes the validation logic much more complex than it would otherwise be since I can't return the result till the timeout is done.

Any suggestions?

P.S. I'm tempted to use the sleep function mentioned in this question, despite the many protestations that it's evil.

Community
  • 1
  • 1
sprugman
  • 17,781
  • 31
  • 105
  • 160

1 Answers1

0

You can't really have your cake and eat it too. You either code single threaded and block the ui thread (which is what you seem to want to do) or offload all work to a closure that executes asynchroneously and let your ui thread free to do pretty animations.

Personally I choose the second approach. Who cares if you can't return validation results "immediately" if they simply aren't available immediately (if they were we wouldn't be having this conversation). Something like this is what you want:

function validate() {
  var spinner=$('#spinner');

  spinner.show();
  setTimeout(function(){
    // heavy lifting
    spinner.hide();

    // if errors show modal dialogs (also asynchroneuosly) here
  }, 1);

  // and exit immediately, canceling any submits pending
  // until we finish checking the data.
  return false;
}
Blindy
  • 55,135
  • 9
  • 81
  • 120
  • I don't mind waiting for validation results. I just want the stupid UI to show the stupid spinner before it starts the heavy lifting. It's called first in the source fer crissake! :) Your solution is exactly what I've done in the past. The thing that I don't like about it is that I may be checking for validation from multiple places, with different possible code routes depending on the context. (I have validateAndSubmit vs. just validate.) I guess I'll have to pass in a post-validation handler to call after the heavy lifting is done.... – sprugman Sep 15 '11 at 19:58