views:

47

answers:

3

Just on my local machine, trying the run the following script causes my computer to crash... What am I doing wrong?

            (function($) {
            var count = '6824756980';
            while (count > 0) {
                setInterval(function() {
                    $('#showcount').html(Math.floor(count-1));
                    count--;
                }, 1000 );
            }
        })(jQuery);

All I need to do is subtract one from the var "count" and update/display it's value every second.

+3  A: 

what you are doing is setting up 6824756980 timers -> BAD

just do

 $(document).ready(function(){
    var count = 6824756980;
    var timerID = setInterval(function() {
             if(count > 0){
                $('#showcount').html(Math.floor(count-=1));
                count--;
             }
             else clearInterval(timerID);
    }, 1000 );
 });
jAndy
Ah, that did it... Thanks. So why exactly does this work more efficiently?
Josh
Or you can use setTimeout. And the Math.floor isn't needed.
Matthew Flaschen
@Josh, setInterval tells JavaScript to call the function repeatedly at an interval (one second in your case). So if your code didn't crash, it would eventually the function running 6824756980 times every second!
Matthew Flaschen
Now what if I wanted to update "count" by subtracting more than just "1" from it each second? Is there a way to do this rather than count--; ?
Josh
@Matthew: I don't see how setTimeout would help here?@Josh: As I wrote, setInterval is setting up 'async' timers that means you're setting up an enormous large number of timers which all execute that code.. accessing an DOM element that much is crashing most likely.
jAndy
@Josh: yes you can (obama!), I've updated my answer
jAndy
Very nice, thanks everyone for the help in understand what it was that I was doing wrong!
Josh
@jAndy, you use a chain of them. `var func = function(){...}`. In `func`, pass `func` to a new 1-second setTimeout, if the time hasn't run out.
Matthew Flaschen
A: 

In addition to count being a string instead of a number, you're spawning a very large number of Interval functions with while(count > 0) { setInterval ... }

If I understand, you should be checking for count > 0 inside the Interval function, since it runs every second.

cthom06
A: 

Your setInterval is in the wrong place.

It's currently in the body of a while loop which will be looping as fast as your computer can go and each time firing of the function to increment the counter. No wonder it's eating resources.

You only need to call setInterval once.

starskythehutch