Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this while JavaScript loop infinite?

I hate doing this. This is THE small piece to end a large project and my mind is fried...

Here's the code. It checks to see if an element is overflowing and resizes the font. It is supposed to resize it until it doesn't overflow. The condition for the loop seems to be ignored and the browser freezes... I feel that I'm missing something crucial in how jQuery works here.

$.fn.fontBefitting = function() {
    var _elm = $(this)[0];
    var _hasScrollBar = false; 
    while ((_elm.clientHeight < _elm.scrollHeight) || (_elm.clientWidth < _elm.scrollWidth)) {
        var fontSize = $(this).css('fontSize');
        fontSize = parseInt(fontSize.substring(0,fontSize.length-2))*0.95;
        $(this).css('fontSize',fontSize+'px');          
    }

}

Thanks in advance.

like image 698
rpophessagr Avatar asked May 13 '26 22:05

rpophessagr


2 Answers

Change:

 fontSize = parseInt(fontSize.substring(0,fontSize.length-2))*0.95;

to:

 fontSize = parseInt(fontSize.substring(0,fontSize.length-2))-1;

Here's a Working Demo. When the font size reached 10px, 10*.95 was 9.5 which the browser was rounding up to 10px. Thus infinite loop.

like image 199
Joe Avatar answered May 15 '26 10:05

Joe


You need to step through your code in a debugger and actually check your condition values to make sure they are changing how you expect. My guess is _elm.clientHieght and _elm.clientWidth aren't actually changing.

like image 43
Jack Avatar answered May 15 '26 11:05

Jack



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!