Making the font as big as possible without overflowing each div I made a function that makes font sizes in &lt;div&gt;s as big as possible without overflowing. It takes a long time to run. How do I optimize this?

$(document).ready(() =&gt; {
  $('.text-fit').each((index, element) =&gt; {
    let currentElement = $(element);
    let fontSize = 999;
    currentElement.wrapInner("&lt;div class='wrapper'&gt;&lt;/div&gt;");
    while (currentElement.find('.wrapper').innerHeight() &gt; currentElement.innerHeight()) {
      fontSize -= 1;
      currentElement.css('font-size', fontSize + 'px');
    }
  });
});
No particular comment on the style, but FWIW, I had to implement the same thing recently — also in jQuery — and this is how I did it. Assume we have an outer &lt;div&gt; named time_display_div that we don't want to overflow, and nested immediately inside that we have a &lt;span&gt; named time_display_span that we're trying to make as big as possible.

function effective_fraction(span, div) {
    var x = span.width() / div.width();
    var y = span.height() / div.height();
    return Math.max(x, y);
}

function update_display(msg) {
    // Change the text of the time display,
    // and massage the font size until it fills the screen.
    var div = $('#time_display_div');
    var span = $('#time_display_span');
    var font_size = parseInt(span.css('font-size'));
    span.text(msg);
    while (effective_fraction(span, div) &lt; 0.90) {
        font_size += 10;
        span.css('font-size', font_size + 'px');
    }
    while (effective_fraction(span, div) &gt; 0.90) {
        font_size -= 2;
        span.css('font-size', font_size + 'px');
    }
}


Basically the only difference is that I'm skipping through the sizes at ten times the speed you are; and I'm using .height() instead of .innerHeight(), but I can confirm that at least in Safari it makes no difference which one I use.

So at least if anyone comes up with a better solution here, it'll be useful to more people than just yourself. :)