text editor in textarea SLOW - javascript

生来就可爱ヽ(ⅴ<●) 提交于 2020-08-10 08:24:50

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!