holland
holland

Reputation: 2182

Maximum call stack size exceeded, infinite loop

I have three Select2 boxes. When I change one, all the not-clicked ones need to be reset. When I do this, it causes an infinite loop and I get the error listed in the title. How can I solve this?

var group = $(".searchgroup1");

group.on('change', function(){
    var box = group.index($(this));
    group.each(function(index){
        if(box != index){
            $(this).val(null).trigger("change"); // <-- this resets the <select>
            //If I remove the code up here, the infinite loop disappears
        }
    });
});

Upvotes: 1

Views: 2175

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075159

jQuery's trigger (which is what click with no arguments calls) calls the event handlers on the element synchronously. Since you're triggering the event you're handling, you're effectively calling your event handler recursively with no get-out clause, so you run out of stack.

Here's proof that the callback is synchronous:

$("#foo").on("click", function() {
  log("Clicked");
});
log("Clicking");
$("#foo").click();
log("Done clicking");

function log(msg) {
  $("<p>").text(msg).appendTo(document.body);
}
<div id="foo"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

You can make the call asynchronous by wrapping it in a setTimeout:

var $this = $(this);
$this.val(null);
setTimeout(function() {
    $this.trigger("change");
}, 0);

Upvotes: 5

Related Questions