user1937021
user1937021

Reputation: 10781

Add a class every 2.5 seconds to an element

I'm trying to add a class to an element every 2.5 seconds using delay():

$(".play").click(function(e) {
         e.preventDefault();
        $('#productimage').addClass('step1');
        $('#productimage').delay(2500).addClass('step2');
        $('#productimage').delay(5000).addClass('step3');
        $('#productimage').delay(7500).addClass('step4');
        $('#productimage').delay(10000).addClass('step5');
    });

It doesn't seeem to be working because it adds the class step5 straight away. Is this the wrong way to go about it?

Thanks.

Upvotes: 0

Views: 1425

Answers (5)

Johan
Johan

Reputation: 35194

delay() is used for delaying animations. Use setTimeout():

var delay = 0;

for(var i = 0; i<=5; i++){

    setTimeout(function(){
        $('#productimage').addClass('step' + (i+1));
    },delay);

    delay += 2500;
}

Or as @DipeshParmar mentioned, setInterval could be more suited for this scenario. Remember to clear the interval once you're done:

var handle = setInterval(function(){ /* do stuff */  }, 2500);
//When you're done:
clearInterval(handle);

Upvotes: 2

0x_Anakin
0x_Anakin

Reputation: 3269

Try this:

var step = 1;
var myInterval = setInterval(function(){
      if(step > 5){
           clearInterval(myInterval);
           return false;
      }
      $('#productimage').addClass('step'+step);
      step++;

}, 2500);

Upvotes: 0

Afsal
Afsal

Reputation: 349

You can use setTimeout function.

setTimeout(function() {
      // Do something after 5 seconds
}, 2500)

Upvotes: 0

Lix
Lix

Reputation: 47956

You could use setInterval to execute some code at certain intervals. You'll have to define a stopping condition (the number of steps you want - num_steps).

For each iteration, just add the class name that you assembled from the text "step" and the current step the loop is on.

var num_steps = 5;
var cur_step = 1;
var timer = setTimeout( function(){
  $('#productimage').addClass( 'step' + cur_step );
  cur_step += 1;
  if ( cur_step > num_steps ){
    clearInterval( timer );
  }
}, 2500 );

Once we have reached the desired number if iterations, we stop the timer using the clearInterval command.

Upvotes: 0

Dipesh Parmar
Dipesh Parmar

Reputation: 27364

setTimeout(expression, timeout); runs the code/function once after the timeout.

setInterval(expression, timeout); runs the code/function in intervals, with the length of the timeout between them.

'setInterval' vs 'setTimeout'

So use setInterval if you want to perform action periodically.

Upvotes: 1

Related Questions