dantey89
dantey89

Reputation: 2287

delay between function in loop jquery

I have a jQuery function that shows modal boxes:

function ShowAnonce(){
    ...
    jQuery(".ShowAnonce").show();
    jQuery(".ShowAnonce").animate({opacity: 1},300).delay(1800).animate({opacity: 0},300);
}

And what I want to do is to show this box 10 times with different random intervals. I used a for loop and setTimeout like this:

for(i=0;i<10;i++){  
    setTimeout(ShowAnonce(),Math.random()*100);
}

but it shows the box 10 times with no delay. What can I do to fix it?

Also, why can't I do the following at the end of ShowAnonce function?

    jQuery(".ShowAnonce").hide();

If I do it, it doesn't shows me box because style display:none keeps being assigned.

Upvotes: 0

Views: 51

Answers (3)

dantey89
dantey89

Reputation: 2287

Another post about each() iteration gave me an answer. So it works for me:

    var time = 0;

    for(i=0;i<10;i++){
        time = time + Math.random() *10000;
        setTimeout(ShowAnonce, time);
    }

Upvotes: 0

Guruprasad J Rao
Guruprasad J Rao

Reputation: 29683

As an alternative you can use setInterval as below instead of for loop for x number of times:

var x = 0;
var intervalID = setInterval(function () {
   ShowAnnounce();
   if (++x === 10) {
       window.clearInterval(intervalID);
   }
}, Math.random()*100);

Upvotes: 0

tejesh
tejesh

Reputation: 109

Math.random() can return value in decimals also like , 0.123. Which the setTimeout() cannot take . Try Math.ceil (Math.random()) this will give you an integer but might give the same value again and again . I would try (Math.ceil (Math.random()) *10 ).

Upvotes: 1

Related Questions