How can I make this jQuery "shrink text" function more efficient? With binary Search?
<p>I've built jQuery function that takes a text string and a width as inputs, then shrinks that piece of text until it's no larger than the width, like so:</p>

<pre><code>function constrain(text, ideal_width){
 var temp = $('.temp_item');
 temp.html(text);
 var item_width = temp.width();
 var ideal = parseInt(ideal_width);
 var smaller_text = text;
 var original = text.length;

 while (item_width &gt; ideal) {
  smaller_text = smaller_text.substr(0, (smaller_text.length-1));
  temp.html(smaller_text);
  item_width = temp.width();
 }

 var final_length = smaller_text.length;
 if (final_length != original) {
  return (smaller_text + '&amp;hellip;');
 } else {
     return text;
 }
}
</code></pre>

<p>This works fine, but because I'm calling the function on many pieces of texts, on any browser except Safari 4 and Chrome, it's really slow.</p>

<p>I've tried using a binary search method to make this more efficient, but what I have so far brings up a slow script dialog in my browser:</p>

<pre><code>function constrain(text, ideal_width){
    var temp = $('.temp_item');
    temp.html(text);
 var item_width = temp.width();
 var ideal = parseInt(ideal_width);

    var lower = 0;
    var original = text.length;
 var higher = text.length;

    while (item_width != ideal) {

     var mid = parseInt((lower + higher) / 2);
        var smaller_text = text.substr(0, mid);
     temp.html(smaller_text);
     item_width = temp.width();

        if (item_width &gt; ideal) {

            // make smaller to the mean of "lower" and this
            higher = mid - 1;

  } else {

      // make larger to the mean of "higher" and this
      lower = mid + 1;

     }
    }

    var final_length = smaller_text.length;
 if (final_length != original) {
  return (smaller_text + '&amp;hellip;');
 } else {
     return text;
 }
}
</code></pre>

<p>Does anyone have an idea of what I should be doing to make this function as efficient as possible?</p>

<p>Thanks! Simon</p>
