javascriptinputmicrotime

Update Input field value with javascript


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">

Solution

  • Couple of issues you have:

    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.