Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 6 of 6
  1. #1
    New Coder
    Join Date
    Sep 2011
    Location
    United Kingdom
    Posts
    74
    Thanks
    2
    Thanked 3 Times in 3 Posts

    setTimeout() withing a for ( ) loop

    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

  • #2
    Kor
    Kor is offline
    Red Devil Mod Kor's Avatar
    Join Date
    Apr 2003
    Location
    Bucharest, ROMANIA
    Posts
    8,478
    Thanks
    58
    Thanked 379 Times in 375 Posts
    You need a function
    Code:
    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);
    KOR
    Offshore programming
    -*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*

  • #3
    New Coder
    Join Date
    Sep 2011
    Location
    United Kingdom
    Posts
    74
    Thanks
    2
    Thanked 3 Times in 3 Posts
    Thanks

  • #4
    New Coder
    Join Date
    Sep 2011
    Location
    United Kingdom
    Posts
    74
    Thanks
    2
    Thanked 3 Times in 3 Posts

    Didn't work, I think because of the browser.

    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 !

  • #5
    Regular Coder
    Join Date
    Sep 2011
    Location
    Sweden
    Posts
    154
    Thanks
    1
    Thanked 22 Times in 22 Posts
    Try
    Code:
    <!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>

  • #6
    New Coder
    Join Date
    Sep 2011
    Location
    United Kingdom
    Posts
    74
    Thanks
    2
    Thanked 3 Times in 3 Posts

    Smile

    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 .


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •