mercredi 18 décembre 2019

Javascript "for" loop issue when using ajax, the loop has access even when condition is false

Working with laravel, the system we were developing was crashing on this view on the "onready" event. After looking at the code, we found the problem was inside the for loop.

$(document).ready(function() {
var url = "";
$.ajax({
  url : url,
  type : "GET"
})
.done(function(data) {
  for (var j = 0; j < data.auctions.length; j++) {
    ...
    $('#object').downCount(data.auctions[j].auction, {
      startDate: data.auctions[j].startDate,
      endDate: data.auctions[j].endDate,
      offset: data.auctions[j].offset
    }, function() {
        //Class management to show the auctions
        finishedAuctions.push(data.auctions[j].auction);
        $('#countdown-bg-'+data.auctions[j].auction).removeClass('bg-primary');
        $('#countdown-bg-'+data.auctions[j].auction).addClass('bg-secondary');
        $('#progress-'+data.auctions[j].auction).removeClass('bg-primary');
        $('#progress-'+data.auctions[j].auction).addClass('bg-secondary');
    });
  }
});

This works perfect for what we needed... But, assuming there exist 3 available auctions, data.auctions.length will have a value of 3, and doing a console.log('value of j: ' + j) to debug the for loop, it somehow prints:

value of j: 0
value of j: 1
value of j: 2
value of j: 3

and then crashes as it tries to reach index 3 of an array with size 3 (0,1,2).

A pseudo fix we made is a try catch code block, as this problem persisted no matter how many items there existed in the array and it always reached the last index + 1:

$(document).ready(function() {
    var url = "";
    $.ajax({
      url : url,
      type : "GET"
    })
    .done(function(data) {
      for (var j = 0; j < data.auctions.length; j++) {
        ...
        $('#object').downCount(data.auctions[j].auction, {
          startDate: data.auctions[j].startDate,
          endDate: data.auctions[j].endDate,
          offset: data.auctions[j].offset
        }, function() {// Try Catch to fix unknown problem with loop
          try {
            finishedAuctions.push(data.auctions[j].auction);
            $('#countdown-bg-'+data.auctions[j].auction).removeClass('bg-primary');
            $('#countdown-bg-'+data.auctions[j].auction).addClass('bg-secondary');
            $('#progress-'+data.auctions[j].auction).removeClass('bg-primary');
            $('#progress-'+data.auctions[j].auction).addClass('bg-secondary');
          } catch (e) {
            //here the index exception is prevented and the view won't crash.
          }
        });
      }
    });

Simple and stupid fix we made, but we haven't found out WHY this is happening, how is the for loop, assuming data.auctions.length = 3, printing 0,1,2,3?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire