javascript 10 秒后添加课程

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20135543/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 17:49:27  来源:igfitidea点击:

Add class after 10 seconds

javascriptjquery

提问by wesbos

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'.

我有一个 div,当我点击它时,它会添加一类“播放”。然后,10 秒后,我想添加一类“完成”。

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

我有这个代码,但我如何在 10 秒后计时,它会添加 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 HackerYouhow to use stackoverflow to get top notch help from the community.

非常感谢大家。我用这个问题向HackerYou 的大约 30 名学生展示了如何使用 stackoverflow 从社区获得一流的帮助。

回答by PSL

Try using setTimeout specifying 10 seconds delay.

尝试使用 setTimeout 指定 10 秒延迟。

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

回答by Arun P Johny

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

您可以将.delay().queue()一起使用

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

Demo: Fiddle

演示:小提琴

回答by Austin Brunkhorst

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

您可以使用该setTimeout()函数在 10 秒后调用回调函数。

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);
});