JeVic JeVic - 3 months ago 9
Javascript Question

Generating number after a set of interval

I am trying to display random number like every after 20 seconds. The code I have below only display when the browser is refresh. What I would like to happen is the number change without refreshing the browser on an infinite loop ranging from 1 - 100

function visitorounter(){
var randomnumber=Math.floor(Math.random()*100);
document.write("<strong>"+randomnumber+"</strong>");
}

visitorounter()

Answer

The problem with your own approach is likely to be the use of document.write after the document has – presumably – finished loading; which either causes the page to be reloaded to show, or entirely over-written by, the supplied string of HTML.

I'd suggest the following approach (as one of many alternatives):

// using a named function to generate the random numbers:
function randomNumber () {
    return Math.floor(Math.random() * 100);
}
function visitorounter() {

    // retrieving the element in which the random number
    // should be shown:
    var elem = document.getElementById('randomNumber');

    // updating that element's text-content to show the
    // first random number immediately:
    elem.textContent = randomNumber();

    // setting the interval (20000ms) after which the
    // the supplied anonymous function should be run:
    window.setInterval(function () {

        // updating the text of the element:
        elem.textContent = randomNumber();
    }, 20000);
}

visitorounter();

function randomNumber() {
  return Math.floor(Math.random() * 100);
}

function visitorounter() {
  var elem = document.getElementById('randomNumber');
  elem.textContent = randomNumber();
  window.setInterval(function() {
    elem.textContent = randomNumber();
  }, 20000);
}

visitorounter();
<p id="randomNumber"></p>

External JS Fiddle demo for experimentation and development.

References:

Comments