0

I am working on autosaving a form using jQuery. This form will keep saving data every 1 min. However, I don't want to spam the database if the user has that browser open for one day. So I want to kill the autosave option if there is no change or if the browser has been open for 30 min.

Anyway I can kill this autosave function?

$("form input").on("input propertychange change", function() {

  var start = $.now();

  setTimeout(autoSaveForm(start), 10000);
});

function autoSaveForm(start) {
  var uuid = $("#uuid").html();
  $.ajax({
    type: "POST",
    url: "trailers/" + uuid + "/save-draft",
    data: $("form").serialize(),
    success: function() {
    }
  });

  if ($.now() - start <= 600000) {
    setTimeout(autoSaveForm(start), 60000);
  }
  else {
    return;
  }
}
LOCKLOCK
  • 341
  • 1
  • 3
  • 13

1 Answers1

1

Yes, you can cancel a timeout with clearTimeout.

Also, you will need to setup a timestamp variable, so your autoSaveForm will check if 30 min have not passed since that timestamp and it can proceed with saving the form. If the time has passed simply stop execution with return and the next setTimeout will not be set.

Even better would be to change your approach, and only save data after any change was made to your form. You can do that with listening keyup and change events on your form inputs. If you fear that your auto-save function will be fired too often, you should make it not run more often than at least several seconds for example. That is done with a throttle function, example of which is in an underscore library: _.throttle.

And here's some code: http://jsfiddle.net/yuraji/4pnbr4bd/ - it updates only on user input and never more often that 1 second.

Yura
  • 2,690
  • 26
  • 32
  • Thanks! My form is a nested and nested form. Form change function is not reacting to changes in nested fields. I have updated my code according to your instruction. Can you take a look? – LOCKLOCK Oct 22 '15 at 03:17
  • 1
    Note, that may probably confuse someone who comes back to the form in an hour. Something else you can do is update the timestamp on a user action. – Yura Oct 22 '15 at 05:03
  • Hi, I have updated the code and it is still not working. It keeps sending ajax request to the server non-stop without delay....Can you take a look? – LOCKLOCK Oct 22 '15 at 15:15
  • That is because your current code sets a new `setTimeout` on _every_ change, and then every of those keep calling themselves endlessly. You might just `throttle` your function. Something like `autoSaveForm = _.throttle(autoSaveForm, 1000)`, which will at least make sure it doesn't run too often. – Yura Oct 22 '15 at 16:37