Adding class after random delay

2019-09-16 04:30发布

问题:

I have been trying to add classes to DIV's after X-amount delay. The reason I want to do this is to let CSS do animations for me (constantly fading in and out for a 'breathing' effect).

The result of this code is that ALL the DIV's start at the same time, so basically it doesnt add the random delay that I want ->

$('.project').each(function() {
var number = 1000 + Math.floor(Math.random() * 6000);
$(this).delay(number).addClass('fading');});

This code (after about 200 on-screen messages) works:

$('.project').each(function() {
var number = 1000 + Math.floor(Math.random() * 6000);
alert(number);
$(this).delay(number).addClass('fading');});

Help would be greatly appreciated :] Thanks!

回答1:

delay works on animations and effects, it doesn't affect addClass, you could try a setTimeout method instead.

 var $this = $(this);
 setTimeout(function(){$this.addClass('fading');}, number);