How to execute a function 5 seconds after the last keystroke?

I have a text box and am trying to create autosave for it. I want to save the contents of such a text area if 5 seconds have passed and there was no key press:

function autosaving(){

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

}

And here is the text box:

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

I want to execute this function 5 seconds after I inserted the last character in this text box. In other words, I want to run this function if 5 seconds have passed and there is no new value in the text box. How can i do this?

+4
source share
2 answers

Use a combination of keyUpandsetTimeout

var timer;
$("textarea").on("keyup", function() {
    clearInterval(timer);
    timer = setTimeout(function() {
        autosaving();
    }, 5 * 1000);
});
+3
source

Try something like this:

var to = null;
$(".mytextarea").on("keypress", function(){
   if(to !== null) clearTimeout(to);
   to = setTimeout(function(){
       autosaving();
       to = null;
   }, 5000);
});
+2
source

All Articles