0

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.

user1937021
  • 10,151
  • 22
  • 81
  • 143

5 Answers5

2

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);
Johan
  • 35,120
  • 54
  • 178
  • 293
1

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.

Community
  • 1
  • 1
Dipesh Parmar
  • 27,090
  • 8
  • 61
  • 90
0

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.

Lix
  • 47,311
  • 12
  • 103
  • 131
0

You can use setTimeout function.

setTimeout(function() {
      // Do something after 5 seconds
}, 2500)
Afsal
  • 349
  • 3
  • 10
0

Try this:

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

}, 2500);
0x_Anakin
  • 3,229
  • 5
  • 47
  • 86