I want a variable to update every second to the value of Math.floor(jeans + jps)
with jeans
being the number of jeans and jps
being the number of jeans produced per second.
Here is a code snippet from my script:
setInterval(function() {
var prefloor = (jeans + jps);
jeans = Math.floor(prefloor);
}, 1000);
However, this does not change the value of jeans
. The following does change it, though:
setInterval(function() {
var prefloor = (jeans + jps);
jeans = prefloor;
}, 1000);
What am I doing wrong?
The problem is your delta value (jps) will be floored to 0 if it is <= 1. Therefore, jeans will be changing by a value of 0, thus remaining constant.
Here's a JSFiddle where the value of Jeans changes when jsp >= 1:
It works fine for this value, but decimal values will be rounded down, thus causing some inconsistencies.
To get the behavior you're probably looking for, what you're going to want to do is make a precise variable (not rounded), and then floor that value when displaying.
For instance:
var jeans=0;
var jps=0;
element.onclick=function(){jps+=0.2}
setInterval(function(){
jeans+=jps;
document.getElementById("jcount").innerHTML=Math.floor(jeans); //use Math.floor only for display
},1000)