问题
I have a html table which gets its values from a database through jQuery Ajax. Something like this
<div id="tableId"></div>
Than the java script:
function showUser(rowsToShow) {
request = $.get("showTableFunction.php", {
q: rowsToShow
});
request.done(function(response, textStatus, jqXHR) {
$("#tableId").html(response);
});
request.fail(function(jqXHR, textStatus, errorThrown) {
console.log("The following error occurred: " + textStatus, errorThrown);
});
}
The table has a oninput function which updated the database every time the user changes the value of one of the cells.
function updateCell(data) {
var cellId= data.id;
var editValue = $(data).text();
requestEdit = $.post("editCellFunction.php", {
cellId: cellId,
editValue: editValue,
});
requestEdit.done(function(response, textStatus, jqXHR) {
console.log(textStatus);
});
requestEdit.fail(function(jqXHR, textStatus, errorThrown) {
console.log("The following error occurred: " + textStatus, errorThrown);
});
}
However this causes a major load on the website. So I want to add a delay that only if there was no new input for lets say 5 seconds it will execute the Ajax request
Would greatly appreciate it sometime can help with this.
回答1:
I actually just implemented something really similar. Basically, you want to set a timer via setTimeout that starts and resets when you receive an input.
const input = document.getElementById('input');
const output = document.getElementById('output');
let timer = null;
function updateDatabase() {
// your code here, but for this example, I'll just change some text.
output.textContent = input.value;
}
function restartTimer() {
clearTimeout(timer);
timer = setTimeout(updateDatabase, 300);
}
input.addEventListener('input', restartTimer);
<input type="text" id="input">
<p>Sent:</p>
<p id="output"></p>
来源:https://stackoverflow.com/questions/59204338/javascript-jquery-delay-oninput