0

I am trying to build a javascript function that will update an input field every second with a new number. This is essentially what I'm hoping my function can do, and hopefully someone can give me a pointer about what I'm doing wrong.

<script>
   var myVar = setInterval(function(){ getNumber() }, 1000);

   function getNumber() {
     var x = round(microtime(true) * 1000);;
     document.getElementById("displaynum").value = x;

</script>

<input type="text" id="displaynum">

2 Answers2

1

Couple of issues you have:

  • Closing bracket for the function
  • It is Math.round() and not just round()
  • What is microtime()? I have replaced it with Math.random() to generate a random number.

var myVar = setInterval(function() {
  getNumber()
}, 1000);

function getNumber() {
  var ts = new Date().getTime();
  var x = Math.round(ts*Math.random());
  document.getElementById("displaynum").value = x;
}
<input type="text" id="displaynum">

Update:

Use new Date().getTime() to get the current time stamp and couple it with Math.random() to get a random number with least probability to get repeated.

void
  • 36,090
  • 8
  • 62
  • 107
  • Those are great points, thanks! Good code. I was using microtime(), which is a php function, to continuously track time so I never generate a duplicate number...if that makes any sense – PhysicsIsRelativelyCool Mar 02 '18 at 20:23
  • @PhysicsIsRelativelyCool see the updated answer. Using `new Date().getTime()` to get the unix timestamp now.. – void Mar 02 '18 at 20:26
0

Your approach is correct, but you have some issue with your code such as an undefined function microtime.

I've replaced microtime with a simple counter for the purpose of the example:

var increment = getNumber();
var input = document.getElementById('displaynum');

var myVar = setInterval(function() {
  input.value = increment();
}, 1000);

function getNumber() {
  var x = 0;
  return function() {
    return x++;
  }
}
<input id="displaynum" type="text" />
Tom O.
  • 5,730
  • 2
  • 21
  • 35
  • I really like this code, and it tracks the number sequentially. Is there a way to continue the count indefinitely? or only when the browser is open? – PhysicsIsRelativelyCool Mar 02 '18 at 21:07
  • The program above will increment indefinitely since there is no condition in the code telling it to stop. Since this code runs in a web browser, it will be terminated when the browser is closed. – Tom O. Mar 02 '18 at 21:13
  • If you're interested in the technique used to create the counter then you should read up on javascript closures: https://www.w3schools.com/js/js_function_closures.asp – Tom O. Mar 02 '18 at 21:17