Cosmicluck
Cosmicluck

Reputation: 481

Javascript math giving incorrect results, how can I fix this?

So I have an issue with Javascript where it is giving me the wrong numbers when I am executing a function. Basically I have it set so my "Total" is equal to the "Total" plus "persec", persec is the number I wish to have added to "Total" every second. So if "persec" is equal to 4, I want it to add 4 to "Total" every second.

I have a for loop that acts as my timer to click a hidden button the is set to take whatever the persec is and add it to my total. My problem is that after the persec passes a value of 1, it starts to add incorrectly. For example if I have persec set to 2, my total will increase by 4 every second. It should only increase by 2. And for example if persec is set to 3 it will add 9 each second. It seems like it is adding the square of persec to the total and I have no idea why.

Here is the buttons and text that is edited with the Javascript below:

<p>Per second: <span id="persec">0</span></p>
<p>Total: <span id="total">0</span></p>
<button id="totalholder" hidden="true"></button>

Here is my "timer", it is in its own function that doesn't apply to the problem, which is why it seems out of place:

var totalCount;
clearInterval(totalCount);

    totalCount = setInterval(function () {
        if (persec > 0) {
            for (var i = 0; i < persec; i++) {
                $("#totalholder").click();
            }
        }
    }, 1000);

And here is the hidden button the timer presses:

$(function() {
$('#totalholder').click(function(){
    totalHolder1();
});

function totalHolder1() {
var persec = parseInt($('#persec').text());
var total = parseInt($('#total').text());

    total = isNaN(total) ? 0 : total + persec;

    $("#persec").text(persec);
    $("#total").text(total);
}
});

Upvotes: 0

Views: 55

Answers (2)

Barmar
Barmar

Reputation: 781626

Get rid of the loop in the timer function:

totalCount = setInterval(function() {
    var persec = parseInt($("#persec").text(), 10);
    if (persec > 0) {
        $("#totalholder").click();
    }
}, 1000);

In your original code, the click handler increases the total by persec, and the for loop was doing that persec times, which squares it. Since you don't want to do it multiple times, you don't need the loop.

Upvotes: 1

Cosmicluck
Cosmicluck

Reputation: 481

I just accidently fixed it.

All I had to do was change my for loop to:

for (var i = 0; i < persec; i = i + persec)

I am not sure why this fixed it, I have done it the other way before.

Upvotes: 0

Related Questions