How Do I Write This Counter Script in JS?

Hi, I’m very familiar with PHP, but not JS. And I want to write this very simple script, but I don’t really know how to in JS…

I wrote the outline of the script in PHP…

Can somebody show me how I would translate this functionality to JS?

<?php
$num = 107151;
$inc = rand(1, 5);
$sec = rand (1, 5);

//every $sec seconds increase $num by $inc...
//then update countbox with updated num
?>

<div id="countbox"></div>
var num = 107151;
function genRand() {
  var r = Math.floor(Math.random() * 6);
  return r  < 1 ? genRand() || r;
}
window.setInterval(function() {
   num += genRand();
  document.getElementById('countbox').innerHTML = num;
}, genRand());

Note that that should probably not be a DIV, but a SPAN or a P. DIVs are intended to contain other containers, not bare text.

Thanks, it doesn’t seem to work though. Maybe I’m doing something wrong?

I have done it like this:


<span id="entrycount"></span>

<script type="text/javascript">
var num = 107151;
function genRand() {
  var r = Math.floor(Math.random() * 6);
  return r  < 1 ? genRand() || r;
}
window.setInterval(function() {
   num += genRand();
  document.getElementById('entrycount').innerHTML = num;
}, genRand());
</script>

There was just a small syntax error with the ternary conditional statement || should be : and the 2nd param for setInterval should be a number, here’s a working version:

<script type="text/javascript">

var num = 107151;

function genRand() {

  var r = Math.floor(Math.random() * 6);

  return r  < 1 ? genRand() : r;

}

window.setInterval(function() {

   num += genRand();

  document.getElementById('entrycount').innerHTML = num;

}, 1000);

</script> 

Yeah, my mistake with the ternary operator, thanks for pointing it out. But the number for setInterval was correct - the OP wants the interval to also be a random number between 1 and 5, which is why it is set to getRand(), which returns that number.

var num = 107151;
function genRand() {
  var r = Math.floor(Math.random() * 6);
  return r  < 1 ? genRand() : r;
}
window.setInterval(function() {
   num += genRand();
  document.getElementById('countbox').innerHTML = num;
}, genRand());

Ok, great, thanks for helping out