当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - Jquery delay is inconsistent while using inside a setInterval function

问题描述:

I want to fade in different elements of a page one by one with jQuery fadeIn function. It's working but the delay between two fadeIn are not consistent. Randomly some elements appear sooner than the others. What am I doing wrong? I am using the following code to achieve that.

setInterval(function(){

$('.showTime .appr').each(function(index){

$(this).delay(500*index).fadeIn(400);

});

}, 50);

Note: The setInterval function is used because I am waiting for the class 'showTime' to be added to the body tag, by some other function.

网友答案:

By using setInterval() you are causing this code to be called every 50ms, even after the .showTime class has been added which is causing the strange behavior you are seeing. If you assign the result of setInterval() to a variable you can then use clearInterval() on it once the class has been added, and your selector returns DOM elements:

// track the interval so we can clear it
var myInterval;
myInterval = setInterval(function(){
    // try to match elements with the selector
    var elements = $('.showTime .appr');
    // if the length is non-zero...
    if ( elements.length ){
        // clear the interval
        clearInterval(myInterval);
        // run your code
        $('.showTime .appr').each(function(index){
            $(this).delay(500*index).fadeIn(400);
        });
    }
}, 50);

All that said, this is probably not the best design pattern - it would be better to use a callback rather than polling and eating up CPU.

网友答案:

The problem is that by using setInterval, all statements are executed many times in 50 millisecond succession. (You are actually calling delay().fadeIn() several times on each element returned by the selector.) Use setTimout, or what you may want rather is to test for a condition in the setInterval body and when that meets (e.g. the class is added), first stop the interval, then execute the fadeIn functions only once per element.

var intId = setInterval(function(){

    if($(document.body).hasClass(..)) {

      clearInterval(intId);

      $('.showTime .appr').each(function(index) {
          $(this).delay(500*index).fadeIn(400);
      });

    }

}, 50);
分享给朋友:
您可能感兴趣的文章:
随机阅读: