SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Zealot
    Join Date
    Dec 2006
    Posts
    135
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    slowing a while loop: setTimeout doesn't work

    I'm trying to use code to move an object across the screen slowly enough so that the viewer can see it moving as a smooth animation...

    Code:
    var thepos = 50;
    while (thepos > 0) {
    		
    	setTimeout("thepos  -= 5",200);
    	img["Canvas.Left"] = thepos;//sets the location of an object on the screen
    	
    	}
    The problem is that the while loop does not seem to wait for the setTimeout method to complete -- it just continues looping while the setTimeout pause is underway. What's more, it seems like this continuous looping causes setTimeout to not execute correctly. In any case, this does not yield the desired result. I want the object to be smoothly animated from one position to another.

    Is there a way to pause a while loop? Or is there a better way to accomplish this task?

    Thanks for your suggestions.

  2. #2
    SitePoint Zealot
    Join Date
    Dec 2006
    Posts
    135
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I was able to answer this. It appears setTimeout doesn't play so well inside of a while loop. I used setInterval instead and all is well.

  3. #3
    I meant that to happen silver trophybronze trophy Raffles's Avatar
    Join Date
    Sep 2005
    Location
    Tanzania
    Posts
    4,662
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    The first argument for setTimeout and setInterval should be a function. What you should have done is something like this:
    Code javascript:
    var thepos = 50
    var timer = setInterval(function() {
      img["Canvas.Left"] = thepos = thepos - 5;
      if (thepos === 0) clearTimeout(timer);
    }, 200);
    200 would make it a bit slow, so perhaps 50ms would be a better interval.


Bookmarks

Posting Permissions

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