...

View Full Version : setTimeout() withing a for ( ) loop



clausrei
09-23-2011, 01:04 PM
Hi,

this must be simple but I don't get it work. I need to do the following delay within a loop:

var position;
for ( var i=1; i < 100; i++) {
position++;
setTimeout("", 1000); // delay for loop;
} // end for loop;

It does not work, because setTimeout needs always the function parameter within the "".
There must be a way around this !?

Thanks you for your help !

Claus

Kor
09-23-2011, 01:52 PM
You need a function


function setPosition(position){
position++;
if(position<100){
setTimeout(function(){setPosition(position)},1000);
}
}
// and call it once, sending the a value as parameter (as 0, first time, as it will be incremented)
setPosition(0);

clausrei
09-23-2011, 02:29 PM
Thanks

clausrei
09-28-2011, 02:57 PM
Hi, It did not work the way I expected it. I tried it with the following For ... Loop, expecting that "Hello World" would be displayed on the screen with a second delay each time:

function setPosition(position){
position++;
if(position<100){
setTimeout(function(){setPosition(position)},1000);
}
}

function delay()
{

for(var i=1; i<100; i++) {
setPosition(1);
document.write("Hello World");
}

Instead, the browser displays 100 Hello Worlds all at ones. Doesn't matter if the delay is 1 millisecond or 1000.

I tried now everything even writing my own delay function, that looks like that:


function delay() {
var date1 = new Date();
var msec = date1.getMilliseconds();
//document.write(" |msec = "+msec+" ");
var msec2, diff;
var same = true;
while(same) {
var date2 = new Date();
var msec2 = date2.getMilliseconds();
//document.write(" |msec2 = "+msec2+" ");
diff = msec2-msec;
if(diff < 0) {diff=diff+1000;}
//document.write(" |the differnece is : "+diff);
if(diff >= 500) {same=false;}
}
return;
}

function init() {
for(var i=1; i< 3; i++) {
delay();
document.write(" Hello World ");

}
}

onload=init();

It works fine, but it displays hello World at ones in the browser and not with delays. It must be the way the javascript engine works ?! It must processes the whole script first before it loads the page.

That makes especially sense ,because my sailing boat, here in my book, is sailing only with a delay of 10 milliseconds from left to right over the screen:

setTimeout( setSail , 10 );

Which should be such a small time, that should be quite quick, but in fact it sails quite slow. When I change it to "setTimeout( setSail , 1000 );", it hardly moves.

What I tried to do was, with the help of a "for(var i=0; i < 100; i++) { ...}", to let it sail only 100px and stop, but this did not work.

I have to find another solution for this !

ironboy
09-28-2011, 10:06 PM
Try
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
/* animate
* inparamaters: options an object with the following properties
* workFunc - a function to run several times that does the specific work
* totalTime - totalTime this should take in ms (optional - defaults to 1000 ms)
* startValue - a value to start at that will be sent to the workFunc (optional - defaults to 1)
* endValue - a value to end at (optional - defaults to 1)
* steps - number of times to call workFunc (optional - will calculate itself if omitted)
* callbackFunc - function to call when the animation has finished
*/
var animate = function(options){
// variable declarations including defaults
var i, stepSize, stepTime, currVal, stepCo = 0, o = options, interval, defaults = {
workFunc: function(){},
totalTime: 1000,
startValue: 1,
endValue: 1,
steps: false,
callbackFunc: function(){}
};
// transfer default values to options if they are omitted
for (i in defaults){!o[i] && (o[i] = defaults[i])};
// calculate steps if omitted (to occur once every 50ms)
!o.steps && (o.steps = o.totalTime/50);
// calculate stepSize
stepSize = (o.endValue - o.startValue) / (o.steps-1);
// calculate time per steop
stepTime = o.totalTime / o.steps;
// set current value to start value
currVal = o.startValue;
// perform animation
interval = setInterval(function(){
stepCo ++;
stepCo == o.steps && clearInterval(interval);
stepCo == o.steps && (currVal = o.endValue);
o.workFunc(currVal);
stepCo == o.steps && o.callbackFunc();
currVal += stepSize;
},stepTime);
};

// Animation object: Say hello (and a counter number) 20 times in 5 seconds
var sayHello = {
workFunc: function(x){
var d = document.createElement('div');
d.innerHTML = 'Hello ' + x;
document.getElementById('helloDiv').appendChild(d);
},
totalTime: 5000,
startValue: 1,
endValue: 20,
steps:20
};

// Animation object: Move the hellodiv 500px in 1 second
var moveIt = {
workFunc: function(x){
document.getElementById('helloDiv').style.left = x + 'px';
},
totalTime: 1000,
startValue: 1,
endValue: 500
};

// Wait for document to load then run our two animations
// (sayHello and then moveIt)
onload = function(){
sayHello.callbackFunc = function(){animate(moveIt)};
animate(sayHello);
};

</script>
</head>
<body>
<div style="position:absolute;left:0" id="helloDiv"></div>
</body>
</html>

clausrei
09-30-2011, 12:30 PM
Thanks will try ! Have done it like this now :

function goright()
{
obj = document.getElementById("boat");
pos = parseInt( obj.style.left, 10 );
pos=pos+100;
h4z(); //only reason for this function is, I needed to declare
// pos before pos2, that its value does not change any more within the loop of
// h4z()
}

function h4z() {
obj = document.getElementById("boat");
var pos2 = parseInt( obj.style.left, 10 );
pos2++;
if ( pos2 > pos ) { return; }
obj.style.left = pos2 + "px";
setTimeout("h4z()",5);
}

Works fine .



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum