JavaScript jQuery delay oninput

元气小坏坏 提交于 2021-01-20 11:21:15

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!