Using i
to count the array when deleting members from it, only half of the markers are deleted. Try instead:
while( map.popups.length ) { map.removePopup( map.popups[0] ); }
If you want to absolutely make sure that the loop does not repeat forever:
function closePopups() {
This type of limited cycle technology is used in nuclear power plants.
Suppose you have 5 pop-ups.
- popups = 5, i = 0, max.popups.length = 5
- popups = 4, i = 1, max.popups.length = 4
- popups = 3, i = 2, max.popups.length = 3
- popups = 2, i = 3, max.popups.length = 2
The value of i
now exceeds max.popups.length
. The loop ends, but some pop-ups are not closed. (When trying to access the array of pop-ups, there may even have been an error outside the borders ...)
You could write your loop like:
function loop_popups() { for( var i = map.popups.length - 1; i >= 0; i-- ) { map.removePopup(map.popups[i]); }; }
This is no longer compared to a moving target and will run faster than the original loop, because comparisons with zero are faster than comparisons with case (on most computer architectures).
AlexC source share