View Full Version : Animations with loop vs setInterval
Agnus
06-25-2009, 04:55 AM
This is a generic javascript question. Changing element style properties in a loop does not work. For example:
<div id="box" style="position: absolute; width: 50px; height: 20px; background: red;"><div>
<script type="text/javascript">
onload = function() {
var box = document.getElementById('box');
var y = 0;
while (y < 1000) box.style.top = y++;
}
</script>
Now if we replace the loop with this:
setInterval(function() { box.style.top = y++; }, 50);
works alright. Why this is happening?
evant
06-25-2009, 05:02 AM
What do you mean it "doesn't work"? The top of the element gets sets correctly in both cases, but how long do you think it takes to execute a while loop 1000 times?
Ext.onReady(function(){
var el = Ext.getBody().createChild({
tag: 'div',
style: 'background-color: red; width: 100px; height: 100px;position: relative;'
}).dom;
var y = 0, old = new Date();
while (y < 1000){
el.style.top = y++;
}
var d = new Date();
console.log(d.getElapsed(old));
});
On my box it takes 15ms.
Agnus
06-25-2009, 06:08 AM
You are right about that. However even if I increase the loop to last longer, it still doesn't seem to render the individual frames:
while (y < 10000) box.style.top = ++y % 100;
Animal
06-25-2009, 01:09 PM
This is a generic javascript question. Changing element style properties in a loop does not work. For example:
<div id="box" style="position: absolute; width: 50px; height: 20px; background: red;"><div>
<script type="text/javascript">
onload = function() {
var box = document.getElementById('box');
var y = 0;
while (y < 1000) box.style.top = y++;
}
</script>
Now if we replace the loop with this:
setInterval(function() { box.style.top = y++; }, 50);
works alright. Why this is happening?
During the execution of the javascript thread, the browser's appearance is not updated.
It's only when the current event handler ends, and control returns into the browser that it updates the screen.
Agnus
06-26-2009, 03:04 AM
@Animal
Thank you, that sounds like a reasonable explanasion.
vBulletin® v3.8.4, Copyright ©2000-2010, Jelsoft Enterprises Ltd.