Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I execute a function after 5 sec from last keyup?

I have a textarea and I'm trying to create a autosaved for that. I want to save the content of such a textarea if 5 sec passed and no key pressed:

function autosaving(){

    // save the value of text area into localstorage
    alert('saved');

}

And here is the textarea:

<textarea class="mytextarea" rows="4" cols="50"></textarea>

I want to execute that function 5 sec after inserted last character into that textarea. In other word, I want to run that function if 5 sec is passed and there isn't any new value in the textarea. How can I do that?

like image 944
stack Avatar asked Mar 10 '16 00:03

stack


2 Answers

Use a combination of keyUp and setTimeout

var timer;
$("textarea").on("keyup", function() {
    clearInterval(timer);
    timer = setTimeout(function() {
        autosaving();
    }, 5 * 1000);
});
like image 190
Sushanth -- Avatar answered Oct 31 '22 13:10

Sushanth --


Try something like this:

var to = null;
$(".mytextarea").on("keypress", function(){
   if(to !== null) clearTimeout(to);
   to = setTimeout(function(){
       autosaving();
       to = null;
   }, 5000);
});
like image 36
JCOC611 Avatar answered Oct 31 '22 14:10

JCOC611