JavaScript jQuery输入延迟 [英] JavaScript jQuery delay oninput
问题描述
我有一个html表,该表通过jQuery Ajax从数据库中获取其值.像这样
I have a html table which gets its values from a database through jQuery Ajax. Something like this
<div id="tableId"></div>
比Java脚本:
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);
});
}
该表具有oninput函数,每次用户更改其中一个单元格的值时,该函数都会更新数据库.
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);
});
}
但是,这会在网站上造成很大的负担.因此,我想添加一个延迟,即只有在没有新输入的情况下(比如说5秒钟),它才会执行Ajax请求
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.
推荐答案
我实际上只是实现了一些非常相似的东西.基本上,您想通过 setTimeout
设置一个计时器,该计时器在收到输入时启动并重置.
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>
这篇关于JavaScript jQuery输入延迟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!