AJAX更新效率

时间:2014-05-25 00:01:37

标签: jquery ajax

我有一个按钮可以按住以调整数字,该数字将更新数据库中的值。

我担心如果我将AJAX更新放在基本形式的位置,它将尝试按照增量更新多次,这将非常低效。

What is an efficient way to only run the ajax update to the database once the user has not updated the number for x seconds?

JSfiddle

JS / JQ

$('#btn').mousehold( function() {
    num = $('#1').text();
    num = parseFloat(num);
    num = num += 1;

    $('#1').text(num); 

    function updateDatabase() {
         //AJAX update here   
    }

});

1 个答案:

答案 0 :(得分:1)

是的,它会提出很多要求。

我建议你使用setTimeout。每次清除timer。并且,如果它没有清除1秒,它就会运行AJAX请求。

var timer;
$('#btn').mousehold( function() {
    var num = $('#1').text();
    num = parseFloat(num) + 1;

    $('#1').text(num); 

    clearTimeout(timer);
    timer = setTimeout(function(){
        //AJAX REQUEST HERE
    },1000);

});
相关问题