0
\$\begingroup\$

I just started making a basic game in HTML, CSS, Javascript, and JQuery, but I want to have the money add up after a certain amount of time (if you have ever played an idle game, you'd know what i mean) but i cant figure this out.

If anyone could help me out, i would appreciate that.

<!DOCTYPE html>
<html>
<head>
    <link rel='stylesheet' href='style.css' />
    <script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js'></script>
    <script src='http://code.jquery.com/jquery-latest.js'></script>
    <script src='script.js'></script>

</head>
<body>
    <div class='Main'>
        <div class='CUR'>
            <p id='CUR1'>Copper Coins: <span id='GC'>0</span></p>
        </div>
    </div>
</body>
<script>
    var max = 100;
    var copper = 0;

    while(copper <= max) {
        setInterval(1000);
        document.getElementById('GC').innerHTML = copper;
        copper++;
    };
</script>
</html>
\$\endgroup\$
1
  • \$\begingroup\$ It looks like your code would work fine. Is there something in particular you would like to improve? If not, your question isn't really on-topic for this site, because open-ended requests for improvement suggestions are unable to be objectively answered. \$\endgroup\$ Jun 30, 2015 at 0:43

2 Answers 2

1
\$\begingroup\$

This is not how setInterval() works. You need to pass the function directly, like this:

setInterval(function() {
    if (copper < max) {
        copper++;
        document.getElementById('GC').innerHTML = copper;
    }
}, 1000);
\$\endgroup\$
3
  • \$\begingroup\$ Ah, thanks, that helps out alot, but when i put that into my code, it for some reason doesnt work \$\endgroup\$ Jun 30, 2015 at 0:17
  • \$\begingroup\$ I accidentally typed getElementId instead of getElementById. Fixed the answer, and verified it works in my browser. \$\endgroup\$
    – simon574
    Jun 30, 2015 at 0:21
  • \$\begingroup\$ You can catch little errors like that easily if you use a Javascript console. Most browsers have this built-in already. \$\endgroup\$
    – simon574
    Jun 30, 2015 at 0:29
1
\$\begingroup\$

setInterval runs forever, or until you cancel it.

This will be a "fire and forget" call. You don't need the loop. The code will run forever, once every few milliseconds.

setInterval(function() {
    // move it up if its too small
    if (copper < max) {
        copper++;
        document.getElementById('GC').innerHTML = copper;
    // move it down if its too big
    } else if (copper > max) {
        copper--;
        document.getElementById('GC').innerHTML = copper;
    }
    // if there is no change to be made, don't bother redrawing the copper amount
}, 10); // do this 100x per second
\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .