最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Add class after 10 seconds - Stack Overflow

programmeradmin9浏览0评论

I have a div where when I click it, it adds a class of 'playing'. Then, after 10 seconds, I want to add a class of 'finished'.

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

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

Any help is appreciated!


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

I have a div where when I click it, it adds a class of 'playing'. Then, after 10 seconds, I want to add a class of 'finished'.

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

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

Any help is appreciated!


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

Share Improve this question edited Nov 22, 2013 at 15:49 wesbos asked Nov 22, 2013 at 1:54 wesboswesbos 26.3k31 gold badges108 silver badges144 bronze badges 2
  • 1 Check out .delay() function. – Yuriy Galanter Commented Nov 22, 2013 at 1:56
  • 1 while you are at it @Wes - remind them to do a bit of research into their problem and ask specific questions (too broad, or not-researched questions tend to get down-voted). Also worth noting that, when possible, posting your code to a service like JSFiddle, JSBin or similar tends to speed up the responses – blurfus Commented Nov 22, 2013 at 17:25
Add a ment  | 

3 Answers 3

Reset to default 14

Try using setTimeout specifying 10 seconds delay.

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

You can use .delay() along with .queue()

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

Demo: Fiddle

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

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)

  1. 暂无评论