1

I'm coding a game that has a 2 minute timer countdown - within that time i want an alert to popup randomly in multiples of 10 seconds. The alert could be called at 10 seconds, 30 seconds or even 110 seconds - as long as they are in multiples of 10.

(function loop() {
    var rand = Math.round(Math.random() * (60000 - 10000)) + 10000;
    setTimeout(function() {
            alert("hi");
            loop();  
    }, rand);
}());

I've found some code whilst doing some research but I don't think I've quite got it right?

Can anyone help?

Thanks Al

1
  • Please describe the error / behaviour you are seeing when you run the code. Commented Mar 9, 2016 at 16:55

1 Answer 1

1

I would do:-

Math.round((Math.random() * 10) + 1); giving you a number 1 and 11

* 10000 to get seconds from 10 to 110, in intervals of 10.

clearTimeout incase the 2nd/3rd/etc timer goes over 2 minutes

var randTimer;

setTimeout(function() {
  alert('Game Over');
  clearTimeout(randTimer);
}, 120000); // 2 minutes

(function randomTimer() {
  var rand = Math.round((Math.random() * 10) + 1); // 1 to 11
  randTimer = setTimeout(function() {
    alert('Random');
    randomTimer();
  }, rand * 10000); // 10 to 110 seconds
}());

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

1 Comment

Works great - I changed 'rand * 10000' to 5000 so that it gets called at least a few times during the 2 minutes. Many thanks

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.