Add class in 10 seconds

I have a div where, when I click on it, it adds a “game” class. Then, after 10 seconds, I want to add a "finished" class.

I have this code, but how to do it, so after 10 seconds it adds the finsihed class?

  $('.albums img').on('click',function(){
    $(this).addClass('playing');
  });

Any help is appreciated!


Thanks a ton to everyone. I used this question to show ~ 30 students at HackerYou how to use stackoverflow to get the fastest help from the community.

+4
source share
3 answers

Try using setTimeout with a delay of 10 seconds.

 $('.albums img').on('click',function(){
    var $this = $(this).addClass('playing');
    window.setTimeout(function(){
        $this.addClass('finsihed');
    }, 10000); //<-- Delay in milliseconds
  });
+11
source

. delay() . queue()

$('.albums img').on('click', function () {
    $(this).addClass('playing').delay(3000).queue(function () {
        $(this).addClass('finsihed')
    });
});

: Fiddle

+2

You can use the function to call the callback function after 10 seconds. setTimeout()

For example.

var timeout = null;

$('.albums img').on('click', function() {
    var self = this;

    $(self).addClass('playing');

    // clear previous timeout if it exists
    timeout && clearTimeout(timeout);

    // set the timeout
    timeout = setTimeout(function() {
        $(self).addClass('finished');

    // 10 seconds
    }, 10e3);
});
0
source

All Articles