Javascript pairing when push is in event handler

Suppose you had an array like:

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

And you need to find id: 232 and delete it so you can:

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

And let there be an event handler that added elements to the array, for example:

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

Is it possible that an event handler can be called as a for loop repeats? If so, then splicing (i, 1) will remove the invalid array index.

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

+4
source share
2 answers

. , : http://jsfiddle.net/wared/ERjJj/. , click ( Chrome).

<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);
});

, - .

+2

for , . - , script , , , script.

+1

Source: https://habr.com/ru/post/1529258/


All Articles