I have a button of which can be held down to adjust a number, and that number will be updating a value in a database.
I am concerned that if i place the AJAX
update where it is in the basic form it will attempt to update many times as per the increment and that would be terribly inefficient.
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?
The JS/JQ
$('#btn').mousehold( function() {
num = $('#1').text();
num = parseFloat(num);
num = num += 1;
$('#1').text(num);
function updateDatabase() {
//AJAX update here
}
});
Yes, it would do a lot of request.
I suggest you tu use a setTimeout. Each time you clear the timer
. And, if it gets 1 seconds without clearing, it run the AJAX request.
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);
});