1

What I am looking for is slightly subjective, but I am sure there is a better way to do this.

I am looking for a better way to perform javascript while a user is typing content into either a textarea or input box on a website. For instance, sites such as Google Docs are capable of saving changes to documents almost instantly without noticeable performance degradation. Many sites however use a bit of jQuery that might look like the following:

$("#element").on("keyup", function() { /* Do something */ });

This works fine for simple things like autocomplete in search boxes, but performance becomes a nightmare once you have any sizable corpus for it to have to deal with (or if a user types fast, yikes).

In trying to find a better way to analyze/save/what-have-you text as the user is typing, I started to do something like this:

var changed = false;
$("#element").on("keyup", function() { changed = true });
setInterval(function() { if(changed) { /* Do something */ changed = false; } }, 1000);

It seems to alleviate laggy or delayed text input, but to me it seems like a less than elegant solution.

So back to my question, is there a better way to have javascript execute when a corpus has been changed? Is there a solution outside of using intervals?

Thanks.

4

3 回答 3

2

有一个jQuery 插件可以完成您所做的工作。您的示例将转换为

$("#element").on("keyup", $.debounce(1000, function() { /* Do something */ }));

该代码将在用户 1000 毫秒内未按任何键后执行。

于 2013-10-21T05:57:18.903 回答
1

我为此找到了一个非常好的解决方案。此代码将检查内容是否已更改,并据此将其保存,否则将不会执行保存功能!

看看这个演示JSFIDDLE

这是代码:

HTML:

Content:<br>
<br>
(type some text into the textarea and it will get saved automatically)
<textarea rows="5" cols="25" id="content"></textarea>
<br>
<span id="sp_msg_saved" style="background-color:yellow; display:none">Content is saved as draft !</span>

JS:

var old_content = "";
function save_content()
{
    var current_content = $('#content').val();
    //check if content has been updated or not
    if(current_content != old_content)
    {
        alert('content is updated ! Save via ajax');
        old_content = current_content;
        $('#sp_msg_saved').show(100);
        $('#sp_msg_saved').fadeOut(3000);
    }
}
setInterval(save_content,3000);

您可以通过更改setInterval函数中的值来增加或减少调用 save 函数的时间。将通过ajax保存内容的代码,将当前用户内容保存到您的数据库中,我没有包括那个......

于 2013-10-21T06:17:48.010 回答
1

你可以使用 window.setTimeout-Function 来做你自己的一点延迟:

var IntervalId = null;

function saveEdits(){
    //Doing your savings...
}

$('input').keyup(function(){
    if (IntervalId){
        window.clearTimeout(IntervalId);
        IntervalId = null;
    }

    IntervalId = window.setTimeout(function(){
        saveEdits();
    }, 3000);
});
于 2013-10-21T07:11:34.343 回答