Question

I've created a character counter for use in the JQuery library to have a similar effect as the Twitter counter (remaining characters left counter). However, I've noticed that at least FireFox has a rough time handling it (other browsers show some strain, but not as bad). Basically, while typing at a steady pace, it'll begin to play 'catch up' and even make the browser unresponsive until it does catch up. When trying the same typing speed in Twitter's textbox, it has no slow down at all!

While I do have an autoresize plugin that watches this box, I've tried many removal and changes to find that only this code is causing the slow down. So, while I can assume it might be too much math for the browser to handle at a certain time, I don't really see why there's a problem with how simple this is, nor can think of a solution.

/* Post Saying text count */
var postSayingLimit = 450;
$('span.counter').text(postSayingLimit);
$('#post-saying').bind('keyup keypress', function() {
    var postSayingUsed = $(this).val().length;
    if(postSayingUsed >= postSayingLimit - postSayingLimit / 10) {
    $(this).parent().find('span.counter').addClass('counter-limit');
    } else {
    $(this).parent().find('span.counter').removeClass('counter-limit');
    }
    var postSayingCount = postSayingLimit - postSayingUsed;
    $(this).parent().find('span.counter').text(postSayingCount);
});

I've tried removing the conditional, going to one binding, and even inserting hard values with it only to continue it's lag. Maybe moving some of the variables out of the bind function? Making the actual counter process into a function as well?

Was it helpful?

Solution

I made an example here: http://jsfiddle.net/zpjc6/

works fast for me (chrome though). i also made a minor improvement by saving the span in an variable. While it's good practice to do so it shouldn't be that expensive though. But maybe it helps.

edit: maybe you could link to your actual site?

OTHER TIPS

You'll want to move as much of the element finding out as possible, and you'll want to only run the class removing if necessary. (Before figuring out an efficient way of determining if it's necessary or not though, it's worth trying to just do away with the repeated searching.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top