Beginning Javascript - While + If/else problem.


    May 23 2012 | 4:24 pm
    Hello Javascript forum!
    I've just started to learn Javascript, and have a specific problem to work on. This is the jist of it is here - http://cycling74.com/forums/topic.php?id=39655
    Below is my code, which all works apart from the query function at the bottom which crashes Max.
    Any ideas?
    // automatically updates js object in max environment
    autowatch = 1;
    //define number of inlets and outlets
    inlets = 1;
    outlets = 1;
    //define variables
    var start_time = new Array();
    var end_time = new Array();
    var mouse_pos = 0;
    // get length of coll to set array length
    function set_length(coll_length)
    {
    start_time.length = coll_length;
    end_time.length = coll_length;
    post(start_time.length, "is the length of the start_time array n");
    }
    // populate the array, x is index, y is value
    function populate(index,start,end)
    {
    start_time[index] = start;
    end_time[index] = end;
    post(start_time[index], end_time[index], "n");
    }
    // check things are working by sending an integer which outputs the data at the index specified.
    function msg_int(x)
    {
    post("The start time at index "+ x + " is equal to " + start_time[x], "n");
    }
    // query
    function query(mouse_x)
    {
    var current_segment = 1;
    while (current_segment
    {
    if (mouse_x >= start_time[current_segment] && mouse_x
    {
    outlet(0, current_segment);
    }
    else
    {
    outlet(0, -1);
    }
    }
    }

    • May 23 2012 | 5:11 pm
      does the post work?
    • May 23 2012 | 5:22 pm
      Yes, everything is fine up until the while loop.
    • May 23 2012 | 7:58 pm
      I changed the mouse_pos declared at the top to mouse_x, so that's not it! Still crashes.
    • May 23 2012 | 8:10 pm
      Looks like your query function is very likely to result in an endless loop (the while loop). What will make it stop looping endlessly, if neither current_segment nor start_time.length is being changed?
    • May 23 2012 | 10:24 pm
      Hi Christoper,
      That makes complete sense, thanks. I needed to increment the loop AND also use 'return 0' when the if statement was true.
      The following appears to work.
      function query(mouse_x)
      {
      var current_segment = 1;
      while (current_segment
      {
      if (mouse_x >= start_time[current_segment] && mouse_x
      {
      outlet(0, current_segment);
      return 0;
      }
      else
      {
      outlet(0, -1);
      current_segment ++;
      }
      }
      }