In a large-scale JavaScript application I have a similar case like this:
var $box = $('#box');
var expensiveOperation = function () {
for (var i = 0; i < 10000; i++) {
for (var j = 0; j < 4500; j++) {
Math.random();
}
}
};
$('#show').click(function () {
$box.show();
expensiveOperation();
});
$('#showDefer').click(function () {
$box.show();
_.defer(expensiveOperation);
});
$('#hide').click(function () {
$box.hide();
expensiveOperation();
});
$('#hideDefer').click(function () {
$box.hide();
_.defer(expensiveOperation);
});
#box {
background-color:red;
width:100px;
height:100px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.7.0/underscore-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="box"></div>
<button id="show">show</button>
<button id="showDefer">show defer</button>
<button id="hide">hide</button>
<button id="hideDefer">hide defer</button>
jsFiddle link, just in case: http://jsfiddle.net/oymaterz/5/
I want to either hide or show a DOM element and the perform an expensive operation. For performance reasons, I want to always ensure that the show/hide are executed first (that is, at the top of the execution stack). This is demonstrated in the example I provided (using underscore's defer) and its working fine under the latest version of Chrome. Also, the above example doesn't work on IE11. Hide/show defer its still slow.
However, when I do the same in my application it works only intermittently and strangely IE11 seems to consistently work fine .
Any ideas as to why I get this behaviour?