JavaScript:如何在不断增长的数组中处理内存?
我有一个相当简单的函数,它可以在每一个键启动时启动。它所做的是在一定条件下(句子很长)标记TinyMCE的输入文本,然后在TinyMCE编辑器中显示突出显示的文本 乍一看,这很有魅力。但是随着文本在数组中的增长,函数的执行时间越来越长 有没有一种很好的方法可以检测输入光标在文本中的位置,然后只分析周围的单词(例如当前的句子)并重用文本的其余部分 代码是这样的 HTMLJavaScript:如何在不断增长的数组中处理内存?,javascript,jquery,tinymce,Javascript,Jquery,Tinymce,我有一个相当简单的函数,它可以在每一个键启动时启动。它所做的是在一定条件下(句子很长)标记TinyMCE的输入文本,然后在TinyMCE编辑器中显示突出显示的文本 乍一看,这很有魅力。但是随着文本在数组中的增长,函数的执行时间越来越长 有没有一种很好的方法可以检测输入光标在文本中的位置,然后只分析周围的单词(例如当前的句子)并重用文本的其余部分 代码是这样的 HTML <div id="myTextArea" contenteditable="true"> Just put lore
<div id="myTextArea" contenteditable="true">
Just put lorem ipsum here.
</div>
欢迎就如何提高这方面的速度提出任何建议:)我发现您的代码有一个问题。使用
onchange
和onkeyup
函数,每次写下一个字母时,都会触发回调两次。
您可以尝试以下几点:
- 如果你只是在分句,为什么不等到一个“.”写下来,然后触发你的循环呢
- 如果使用长度缓存,循环应该更快,但如果数组非常长,则循环的性能应该更高<代码>用于(变量i=0,len=sentenceArray.length;i
- 你应该使用去盎司函数。这样,您可以在定义的时间内或在每次键控或更改时触发循环一次。检查David Walsh的去盎司功能:
干杯 很好。我花了一段时间才弄明白去抖器是如何工作的。但现在它就像一个符咒:)更流畅。我不想只在(……等等)上跑步,因为人们经常在句子中间停止打字。我想尽快验证文本:)去Bouncer是以有效方式实现这一目标的完美方式。在@Jorge使用去Bouncer功能时,我的Chrome Inspect工具在尝试检查时会不断暂停。我是不是用错了,或者这是意料之中的事?
tinymce.init({
selector: '#myTextArea',
height: 300,
setup: function(ed) {
ed.on('change', myCustomInitInstance);
ed.on('keyup', myCustomInitInstance);
ed.on('paste', myCustomInitInstance);
ed.on('cut', myCustomInitInstance);
},
init_instance_callback: "myCustomInitInstance",
});
function myCustomInitInstance(inst) {
var rawText = tinyMCE.get('myTextArea').getContent({
format: 'text'
});
var sentenceArray = rawText.split(".");
var matchWarning = [];
var longSentence = 16;
var words;
var wordCounter;
var output;
for (var i in sentenceArray) {
words = sentenceArray[i].split(" ");
wordCounter = words.length;
if (wordCounter > longSentence) {
matchWarning.push(sentenceArray[i]);
}
}
var editor = tinyMCE.activeEditor;
// Store the selection
var bookmark = editor.selection.getBookmark();
// Remove previous marks and add new ones
$(editor.getBody()).unmark().mark(matchWarning, {
acrossElements: true,
"separateWordSearch": false,
});
// Restore the selection
editor.selection.moveToBookmark(bookmark);
}
// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds. If `immediate` is passed, trigger the function on the
// leading edge, instead of the trailing.
function debounce(func, wait, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
};