0

I am trying to generate random numbers using Math.random() that are logged / or written in random intervals...

I wrote the following:

function ranNum () {
  setInterval( function () {
  var myNum = Math.round(Math.random()*100000);
  document.write(myNum+' ');
  return myNum;
  }, ranNum)
}

ranNum();

but the intervals are not random, in fact they seem to be null or zero, as there are endless numbers printed... I guess it's not possible to call a new instance of the ranNum function so the second parameter of setInterval is either 0 or always the same..

I was told recursion would be the solution here but fail to implement it.

2
  • 1
    use setTimeout instead setInterval Commented Oct 12, 2014 at 9:01
  • can't I randomize the interval period? Commented Oct 12, 2014 at 9:24

2 Answers 2

1

As monkeyinsight points it, use setTimeout:

function ranNum () {
  setTimeout( function () {
  var myNum = Math.round(Math.random()*100000);
  document.write(myNum+' ');
  ranNum(); //This makes the function call `recursive` (in a broad sense)
  return myNum;
  }, Math.round(Math.random()*10000) // The function in the setTimeout will be called in 0-10000ms
  );
}

ranNum();
Sign up to request clarification or add additional context in comments.

1 Comment

I am choosing your answer because it was closer to my code / recursion, if even the other one seems more solid..
1

If you want a random interval, use repeated setTimeout. setInterval just repeats on the same interval.

function ranNum () {
  schedule();
  function schedule() {
    setTimeout(go, Math.random() * 10000);
  }
  function go() {
    var myNum = Math.round(Math.random()*100000);
    document.write(myNum+' ');
    schedule();
    // No return, it doesn't make any sense to return something from a timer function
  }
}

Side note: You don't want document.write for this. Your document will be replaced by the document.write after the first timer function calls. Instead, use modern DOM techniques like appendChild or insertAdjacentHTML.

var counter = 20;
function ranNum () {
  schedule();
  function schedule() {
    setTimeout(go, Math.random() * 10000);
  }
  function go() {
    var myNum = Math.round(Math.random()*100000);
    display(myNum+' ');
    if (--counter > 0) { // For the snippet, stop after 20
      schedule();
    }
    // No return, it doesn't make any sense to return something from a timer function
  }
}
function display(msg) {
  document.body.insertAdjacentHTML("beforeend", msg);
}
ranNum();

1 Comment

thanks, no worries about document.write, it's not a real-life project, I'm just using it instead of console.logging :)

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.