问题
I'm implementing a simple ( not rich ) text editor in html using a fixed size ( doesn't automatically grow ) textarea. I have made a pagination system which splits the text to fit that textarea. With relativelay large texts ( 20 pages = 20 textareas ) the function takes about 100ms in total for those 20 pages ( less if there is less text ). the logic is like this:
function paginate() {
clienth = textarea.clientheight;
while (maxTextSize>minTextSize+1) {
textarea.value = text;
// a binary subdivision algorithm which runs in logarithmic time
if (textarea.scrollheight>clienth) {
text = newsmallertext;
} else {
text = newbiggertext;
}
maxTextSize = newvalue1;
minTextSize = newvalue2;
}
}
so for about 14 KB of text ( 19pages ), the function gets called 187 times ( 10 times per page ) with a time of about 100ms for firefox, ~60ms for chrome and opera and about 200ms for IE. Of those 100ms, about 40ms are spent for assigning the text to the textarea ( .value = blabla ) and the rest 60 for checking if the scrollheight is bigger than clientheight. So, 99% of the time is spent there.
That doesn't SEEM a lot but it is. Why ? Because I need to call that function EVERY TIME a user types ( presses a key ) in the textarea in order to apply the new text accordingly. The user may type a letter, backspace, delete, hit enter and so on and so forth. So for each keydown i call the paginate function again to calculate the new text that fits the textarea. Which makes typing VERY SLOW since for each pressed key there is a delay of 100ms.
So I was wondering if there is an optimization for assigning the text to the textarea or checking scrollheight, or a TOTALLY different way for this.
Thank you in advance for all suggestions.
please do not suggest to make the textarea automatically grow, it's NOT in the requirements.
edit: made the while() loop more clear about what it does.
来源:https://stackoverflow.com/questions/12471905/text-editor-in-textarea-slow-javascript