Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setInterval after textarea input changes

I'd like to save a textareas information after the input changes and after 2 seconds.

I tried it using this code:

jQuery('#textarea').on('input propertychange paste', function() {
    setInterval(function() {
        //save
     }, 2000);
});

but it wasn't very effective, as the there seemed to be some sort of infinite loop that I had created.

Any ideas? Thanks

like image 649
Jamie Avatar asked Aug 10 '26 17:08

Jamie


1 Answers

First of all you need to use setTimeout instead of setInterval. Then you need to clear previous timer if there are new changes in textarea. For example something like this:

jQuery('#textarea').on('input propertychange paste', function() {

    // Clear previous timeout
    if ($(this).data('timeout')) {
        clearTimeout($(this).data('timeout'));
    }

    // Set up new one
    $(this).data('timeout', setTimeout(function() {
        //save
     }, 2000));
});
like image 144
dfsq Avatar answered Aug 13 '26 05:08

dfsq