0

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.

5
  • use setTimeout(ShowAnonce, Math.random()*100); instead of setTimeout(ShowAnonce(),Math.random()*100); Commented May 19, 2015 at 9:18
  • you should pass the function but you passed the return value (undefined) Commented May 19, 2015 at 9:18
  • Just as @marcel writes. If you use "()" after your function it will be called when the browser gets there. You have to use just the name of the function. Commented May 19, 2015 at 9:19
  • ok, I fixed it. But setTimeout works only for a first time. So I have delay, for example 8 second, when it's expired it begen to show boxes without no delay Commented May 19, 2015 at 9:27
  • @dantey89, did you want something like this? Let me know :) Commented May 19, 2015 at 11:01

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

You messed up your brackets, Math.ceil (Math.random()) *10 will just give you 10 every time.
Yeah I was typing from mobile sorry .
0

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.