Fortuna Iwasaki
Fortuna Iwasaki

Reputation: 141

Creating a random number generator in HTML

I'm trying to create a webpage the looks like a health monitor and I need to create a random number generator that will act as the heart monitor. Here is what I have:

<?php

function functionName()
{
    return rand(5, 15);
}

?>

<html>
<body>

<?php 

    $i = 0;

while ($i <= 10) 
{
    echo functionName();
    echo "</br>";
    $i++;
}

?>


</body>
</html>

The problem is that number are printed one after another and I need them to just show up in the same place but be different. In other words if I have a section that says "Heart Best Per Seconds: ", I will need a new number to show up there every few seconds in place of the other.

Does anyone know how to do this? I've seen things similar to this so I'm pretty sure that it's doable.

Upvotes: 4

Views: 4143

Answers (3)

Munawir
Munawir

Reputation: 3356

You can generate random numbers using Math.random().

Round a number downward to its nearest integer using Math.floor().

And use setInterval() to run the function at particular interval.

setInterval(function() {
  var i = Math.floor(Math.random() * (15 - 5 + 1)) + 5;
  document.getElementById("hbeat").innerHTML = 'Heart Beat Per Seconds : ' + i;
}, 1000);
<span id="hbeat"></span>

Upvotes: 0

Amin Gharavi
Amin Gharavi

Reputation: 452

setInterval(function() {
  var i = Math.floor(Math.random() * (15 - 5 + 1)) + 5;
  document.getElementById("random").innerHTML = i;
}, 1000);
 <span id="random"></span>

this maybe? using Math.random(); and setInterval()

Upvotes: 3

user3785693
user3785693

Reputation:

To accomplish what you want, you might have to use a combination of JavaScript's JQuery and PHP. For starters, create a file, randomnumber.php

<?php
die(rand(5,15));
?>

and, on your index.php

<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script> <!-- load JQuery from Google CDN -->
    </head>
    <body>
        <h2 id="randomNumber"></h2>
    </body>
    <script>
    function getRandom() {
        setInterval(function() {
            $("#randomNumber").load("randomNumber.php");
        }, 3000) // delay in milliseconds
    }
    getRandom();
    </script>
</html>

Upvotes: 0

Related Questions