简体   繁体   中英

Firing a function every x seconds

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);
    };
})();

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
});

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);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM