Francesco
Francesco

Reputation: 25239

Javascript: nested loops?

I'd like to achieve an animation/sequence like this:

the animation starts with a loop (imagine a car moving from x1 to x2) then a pause of 1 second then again the animation (imagine a car moving from x2 to x3 etc)

the car loop is achieved adding 1px to the car left: value

but i cant figure out the nested loop how should work

i'm trying to do ti only using setInterval, no jquery

UPDATE: sorry i wasnt clear

but assume we have

var animation = setInterval(car_moves, 10);

how do i trigger this animation every 2 seconds, and the animation should last 0.5sec ?

Upvotes: 3

Views: 872

Answers (5)

Cheery
Cheery

Reputation: 16214

Look, this is done with jQuery http://jsfiddle.net/qCx69/

$('img').animate({left: '100px'}, 2000, function() {
    $(this).delay(1000).animate({left: '300px'}, 2000);
});

interacting with

<img src='http://boydstire.com/img/car_img.jpg' id='car'
     style='position:absolute;left:0px;top:100px;'>

or without it (this one is not an optimized solution) http://jsfiddle.net/8bZTA/1/

var timer = setInterval(function(){
    update_car(100,1);
}, 50);

function update_car(x,path)
{
  var car = document.getElementById('car'), 
      pos = parseInt(car.style.left) + 1;
  car.style.left = pos + 'px';
  if (pos > x)  
  {
      clearInterval(timer);
      if (path!=2)
      {
      setTimeout(function(){ //pause
       timer = setInterval(function(){update_car(200,2);}, 50);}
           , 5000);
      }
  }
}

Updated:

You can even make a set of stops and motions (it can be update for variable speed too) http://jsfiddle.net/hFH4U/5/

var timer = setInterval(function(){update_car();}, 50);

var path = {'path1': 100, 'pause1': 2000, 'path2': 200, 
               'pause2': 2000, 'path3': 220}, 
                cur_step = 0, steps = [], speed = 1;
for (var i in path)  steps.push(i);

function update_car()
{
  var car = document.getElementById('car'), 
      pos = parseInt(car.style.left);
  if (/^path/.test(steps[cur_step]))
  {
      // motion part
      if (pos > path[steps[cur_step]])
          cur_step++;
  }
  if (/^pause/.test(steps[cur_step]))
  {
      clearTimeout(timer);
      setTimeout(function(){ 
        cur_step++;
        timer = setInterval(function(){ update_car(); }, 50);
      }, path[steps[cur_step]]);
  }
  if (cur_step >= steps.length) // end animation
      clearInterval(timer);

   car.style.left = (pos + speed) + 'px';
}

Upvotes: 2

chucksmash
chucksmash

Reputation: 5997

Edit: Here's the straight up javascript/html/Css...all you need is a suitable car.jpg file...

<!DOCTYPE html>
<html>
<head>
<title>Hi</title>
<style>
#car {
    position: absolute;
    left: 0px;
}
</style>
<script type="text/javascript">
var last_x = 0;
var some_arbitrary_stopping_point = 200;
var x = self.setInterval("move()", 100);

function move() 
{
    last_x += 5;
    document.getElementById('car').style.left = last_x + 'px';
    check_pos_car();
    return last_x;
}

function check_pos_car()
{
    if (last_x > some_arbitrary_stopping_point)
    {
        x = window.clearInterval(x);
    }
}


</script>
</head>
<body>
<img src="car.jpg" id="car" alt="A beetle">
</body>
</html>

Upvotes: 0

Matt Lo
Matt Lo

Reputation: 5731

Demo: http://jsfiddle.net/MattLo/BVEmF/1/

An object oriented approach:

// example showing linear movement
function car() {
   this.car = document.getElementById("car");
   this.style = this.car.style;
   this.delay = 2000; // 2 secs
   this.position = 0;
}

car.prototype.moveBy = function(m) {
   var me = this;
   setTimeout(function() {
      me.animate(m);
   },this.delay)
}

car.prototype.animate = function(m) {
   var me = this, i=0, 
   r = setInterval(function() {
      ++i;
      me._move(i);
      if(i === m) {
         me.position += i;
         // stop animation
         clearInterval(r);
         // delay again
         me.moveBy(m);
      }
   },77);
}

car.prototype._move = function(i) {
   this.style.marginLeft = i+this.position+"px";
}

Car = new car;
Car.moveBy(20);

Upvotes: 1

StephenPAdams
StephenPAdams

Reputation: 2817

You don't need a nested loop. You can use something like setInterval to accomplish this. Keep in mind I'm using jQuery to get the target element by id.

var interval = setInterval(IncreasePosition, 1000); // 1000 is in milliseconds
function IncreasePosition() {
    var targetElement = $("#targetElementId");
    // TODO: Get current padding value
    // TODO: Increment to it
}

That method (IncreasePosition) will get called every second and increase the padding.

Upvotes: 0

AustinDahl
AustinDahl

Reputation: 852

Instead of writing a traditional loop, you should take a look at setTimeout and setInterval. The first argument to those calls is a function where you would draw the car or move the car.

Upvotes: 0

Related Questions