4

Suppose you had an array like:

var arr= [{id:121, v:'a'}, {id:232, 'b'}];

And you needed to find id: 232 and remove it, so you might do:

for (var i = arr.length; i--;) {
   if (arr[i].id  === 232) {
      arr.splice(i, 1);
   }
};

And suppose there is an event handler which was adding items into the array like:

arr.push( {id:443, 'c'} );   

Is it possible that the event handler might be called as the for loop is iterating? If so, then splice(i,1) would remove the wrong array index.

As javascript is single threaded, is it smart enough to finish the for-loop before handling events?

Brian McGinity
  • 5,777
  • 5
  • 36
  • 46

2 Answers2

2

Interesting question. I've made a small test to check for real : http://jsfiddle.net/wared/ERjJj/. It appears that the click event occurs after the loop is done (tested with Chrome only).

<ol>
    <li>Open your browser console.</li>
    <li>Click <button>start</button>.</li>
    <li>The console prints <code>wait...</code>.</li>
    <li>Click again, one or more times, anywhere in this panel.</li>
    <li>Wait a few seconds until the console prints <code>done!</code>.</li>
    <li>The console prints <code>click</code>.</li>
</ol>
$(document).click(function () {
    console.log('click');
});
$('button').one('click', function click() {
    var i = 0, b = this;
    console.log('wait...');
    while (i++ < 1E10) 1+1;
    console.log('done!');
    setTimeout(function () {
        $(b).one('click', click);
    }, 10);
});

Feel free to let me know if there is any problem.

  • @BrianMcGinity That's right. Better to split into multiple operations. You can use timers to simulate multi-threading, but there must be better ways : http://ejohn.org/blog/how-javascript-timers-work/, http://stackoverflow.com/questions/7639224/javascript-multithreading, https://www.google.fr/search?q=javascript+multi+threading. –  Feb 27 '14 at 18:31
1

unless the for loop actually triggers an event, it will complete before. The variable array is what was available to the script when it ran, so if an event triggers and adds to the array DURING the execution, nothing happens until the next time the script runs.

VikingBlooded
  • 884
  • 1
  • 6
  • 17