• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 583
  • Last Modified:

Random number in Javascript every X seconds

How can I use javascript to generate a random number between X and Y every Z seconds?

I am wanting to make a sort of fake page counter so once the page loads, I am wanting it to say something like "Number of people currently viewing: XXXX"  where XXXX changes every second or so.

Thanks in advance!
1 Solution
This should do the trick.  Credit to the following for saving me some brain time in figuring ranges:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <script type="text/javascript">
  var timer = null;
  function startcounter(low, high, time, targetid){
      generate(low, high, targetid);
      time = time * 1000;
      timer = setInterval("generate(" + low + ", " + high + ", '" + targetid + "')", time);
  function generate(low, high, targetid){
      var target = document.getElementById(targetid);
      var counter = null;
      counter = Math.floor((high - (low - 1)) * Math.random()) + low;
      target.innerHTML = counter;
<body onload="startcounter(100, 110, 1, 'rnum');">
 <div id="rnum">&nbsp;</div>

Open in new window

plasticbrainAuthor Commented:
This is exactly what I was looking for! Thank you for the excellent code snippet.

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now