views:

50

answers:

2

I wrote this:

$('[name=item-title]').live('keyup',function(k){
    char_limit=parseInt($('[data-charlimit]').attr('data-charlimit'));
    total = char_limit-parseInt($(this).val().length);
    $('.charcount span').text(char_limit-parseInt($(this).val().length));
});

But after the first few words it starts going super slow where I'll type and the words will show a millisecond after. If i get to like 250 words it gets nearly 3/4 of a second behind it seems. Any ideas why? To me what i wrote seems fairly minimal...

+2  A: 
  1. If possible, precalculate the char_limit. It won't change during the typing.
  2. Use the total variable in your fourth line, or leave out its calculation completely
  3. Leave out the parseInts except for maybe the first one, they're useless.

This would give you

var char_limit=parseInt($('[data-charlimit]').attr('data-charlimit'));
$('[name=item-title]').live('keyup',function(k){
    $('.charcount span').text(char_limit-$(this).val().length);
});

I'm not sure if there are multiple char_limits though, as this would ruin those. It seems that your current $('[data-charlimit]') approach doesn't allow for those anyway.

MvanGeest
Yeah, the parseInt thing, the first one was needed. But, it's still super slow...
Oscar Godson
+2  A: 

You're doing a DOM traversal per character and you're not sure why it's slow?

// calculate upper limit once -- it won't change, presumably
var char_limit=parseInt($('[data-charlimit]').attr('data-charlimit'));

$('[name=item-title]').live('keyup',function(k){
    // length is already numeric, no need to parse it
    var remaining = char_limit - $(this).val().length;
    $('.charcount span').text( remaining ); // use the result, note I renamed it
});
tvanfosson
WTF, it's still super slow. I don't get why this would be slow. I'm doing WAY more processor heavy things, like modals and constant AJAX calls (this is an app) and they all run fine, but even your code and MvanGeest and mine which isn't even that tough for any browsers anymore is making it slow?
Oscar Godson