views:

79

answers:

3

Hey. I have a code like:

$("#clickMe").click(                                    
     function(){   
          if (i == 1) {            
               i = i+1
               $("#div p").css("left", "-" + width * i + "px");  
            }
});

As you can see -margin changes when somebody clicks a button. What if I want it to happen just on site load every 10 seconds?

Thanks.

+5  A: 

Use setInterval to set up a timed event:

setInterval(
     function(){   
          if (i == 1) {            
               i = i+1
               $("#div p").css("left", "-" + width * i + "px");  
            }
     },
     10000  /* 10000 ms = 10 sec */
);
casablanca
Assign `setInterval()` to a variable, so you can stop it with `clearInterval()` if you want. ==> `var timer = setInterval( ... );`, then to stop: `clearInterval(timer);`
Peter Ajtai
+2  A: 

Using the setInterval function.

Russell Dias
A: 
var cancel_margin_change = false;
$(function() {

   var i = 1, width = 10, xtime = 10000,
      margin_change = function() {

          if (i == 1)
             $("#div p").css("left", "-" + (width * (++i)) + "px");

          if (!cancel_margin_change)
             setTimeout(margin_change, xtime);
       };

   margin_change();  

});
andres descalzo