Update count every second causing massive memory problems
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.
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 );
});
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.
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.
精彩评论