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.
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;
}
精彩评论