3

I am currently using a keyup function to initiate my autosave.php file which auto saves information to a table. However, I am starting to find that the keyup seems to be inefficient due to fast typing and submitting long strings.

How can I have the ajax submit every x seconds, instead of each keyup after so many ms?

$(document).ready(function() { // Handle Auto Save $('.autosaveEdit').keyup(function() { delay(function() { $.ajax({ type: "post", url: "autosave.php", data: $('#ajaxForm').serialize(), success: function(data) { console.log('success!'); } }); }, 500 ); }); }); var delay = (function() { var timer = 0; return function(callback, ms) { clearTimeout (timer); timer = setTimeout(callback, ms); }; })(); 
0

3 Answers 3

3

Solution

Use setInterval It is like setTimeout but repeats itself.

setInterval(function () { $.ajax({ type: "post", url: "autosave.php", data: $('#ajaxForm').serialize(), success: function(data) { console.log('success!'); } }); }, 1000); 

Optimization

turn it on when the control has focus and turn it off when focus leaves. Also poll for the form data if it has updated then send the ajax request otherwise ignore it.

var saveToken; var save = (function () { var form; return function () { var form2 = $('#ajaxForm').serialize(); if (form !== form2) { // the form has updated form = form2; $.ajax({ type: "post", url: "autosave.php", data: form, success: function(data) { console.log('success!'); } }); } } }()); $('.autosaveEdit').focus(function() { saveToken = setInterval(save, 1000); }); $('.autosaveEdit').focusout(function() { clearInterval(saveToken); save(); // one last time }); 
Sign up to request clarification or add additional context in comments.

3 Comments

wouldn't this lead to submission of the same data repetitively? If i were to be editing a form and left my computer for 10 minutes, wouldn't this resubmit the same form several times before I cam back to finish it?
Yes it would let me optimize it a little more
@Brandon Now it polls every second and would for 10 minutes while you are focusing on the element. But no ajax happens unless the form updates.
1

I believe that what you are looking for is the window.setInterval function. It's used like this:

setInterval(function() { console.log('3 seconds later!'); }, 3000); 

Comments

1

Use setInterval

function goSaveIt() { $.ajax({ type: "post", url: "autosave.php", data: $('#ajaxForm').serialize(), success: function(data) { console.log('success!'); } }); } setInterval(goSaveIt, 5000); // 5000 for every 5 seconds 

Comments