I have a following function which slides a relatively positioned element 1000px off of where it is now.
for (var i = 0; i < 1000; i++) {
$('.my-element').css(
'left',
parseInt($('.my-element').css('left'), 10) + 1
);
}
This does not produces a sliding effect. Rather, by the end of the execution, the element moves abruptly 1000px to its right.
Now, if I wrap the UI updates in setTimeout like below:
for (var i = 0; i < 1000; i++) {
setTimeout(function () {
$('.my-element').css(
'left',
parseInt($('.my-element').css('left'), 10) + 1
);
}, 0);
}
This produces the visual effect of the element sliding 1000px to its right.
Now, according to my understaning and this SO thread, Why is setTimeout(fn, 0) sometimes useful?, UI updates are queued in the browser event queue in the same way async callbacks are queued like setTimeout callback.
So, in case first, basically, a queue of 1000 UI updates are made when the for loop is executed.
And in case second, first, a queue of 1000 setTimeout callbacks is created, which on execution, creates another queue of 1000 UI updates.
So, eventually, both cases create the same queue of 1000 UI updates. Then why the difference in the visual result?
I must be looking over some important JavaScipt and browser rendering concept here. Anyone who can enlighten me will be much appreciated.
Note: Above examples are purely for understanding purpose and not an attempt to create a JS function to slide a DOM element.