How to stop long javascript loops from crashing the browser?-Collection of common programming errors
I have a button in my page that’s looping a series of DIVs and editing them (appending text mostly, nothing serious), The thing is, the number of DIVs is changing by the user (The user can add or remove them freely),
I’m looping the DIVs via jQuery $.each function:
var DomToEdit = $('.divs_to_edit');
$.each(DomToEdit, function() { $(this).append('text'); ... });
the variable DomToEdit contains somewhat unlimited number of divs, and then I refer to them via the $.each function.
Sometimes while doing the $.each loop the user gets to wait for a couple of secons, and in worse cases the browser is crashing
Is there a way to prevent this? Maybe having the loop “sleep” after 50 DIVs?
Thanks
EDIT: I didn’t use the same ID, sorry – it was a flaw in my explanation. I use the same class. 🙂
-
The first argument of the function in the
.each
handler is the index of the current element. you can simply add a check before it, andreturn false
to stop the loop.$.each(DomToEdit, function(i) { // or DomToEdit.each(function() { if (i === 50) return false; ..
DomToEdit
is a jQuery object, so$.each(DomToEdit, fn)
andDomToEdit.each(fn)
are equivalent.A more effective method is to cut off the elements, using
.slice(0, 50)
.DomToEdit.slice(0, 50).each( function(i) { ..
-
Whenever I think that code can potentially cause a crash, I’ll create a self-decementing
breaker
variable that breaks out of a loop after a certain number of loop cycles.var breaker = 100; while(true) { breaker--;if(breaker