Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript to randomly add/subtract to a number every second

What I want my function to achieve for my javascript function is for every second to either randomly subtract or add (a random number) to a number held in a div.

Here's what I have so far.

It doesn't work, it seems to append the number to the end of the div value (100), and also it doesn't take into account that I want it to either randomly add or subtract (it just adds at the moment)

    setInterval(function(){
        random = (Math.floor((Math.random()*15)+1)); 
        currentnumber = document.getElementById('number');

        document.getElementById('number').innerHTML =  currentnumber + random;

     }, 1000);
like image 565
J. Podolski Avatar asked Feb 10 '26 23:02

J. Podolski


1 Answers

parse the current value as an integer, and then do another math.random and use it to decide negative or positive. Lastly, you need to use the innerHTML of currentnumber, not the entire node. So something like this should work:

setInterval(function(){
    random = (Math.floor((Math.random()*15)+1));
    var plusOrMinus = Math.random() < 0.5 ? -1 : 1;
    random = random * plusOrMinus; 
    currentnumber = document.getElementById('number');

    document.getElementById('number').innerHTML =  parseInt(currentnumber.innerHTML) + random;

 }, 1000);

WORKING FIDDLE

like image 75
Rooster Avatar answered Feb 13 '26 14:02

Rooster