我有一个包含 Repeater
的表单,其中有一个 RadioButtonList
和一个 TextBox
。当用户更改单选按钮或其中一个文本框中的文本时,所选项目和该中继器项目的关联文本应保存到数据库中。
由于 .change()
函数,单选按钮更改时保存很容易,但是对于 TextBox
我正在创建一个计时器,当文本更改时保存用户停止输入后 2 秒的数据
问题是,如果用户在计时器执行之前离开页面或开始在不同的文本框中键入内容,我需要手动执行计时器。我怎样才能做到这一点?
我的 JavaScript 看起来像这样:
var typingTimer; //timer identifier
var doneTypingInterval = 2000; //time in ms, 2 second for example
$('textarea').on('input', function () {
// Clear timer
clearTimeout(typingTimer);
// Set new timer to save form, passing current repeater item to Save method
var parent = $(this).closest('.my-repeater-section');
typingTimer = setTimeout(function () { saveForm(parent); }, doneTypingInterval);
});
最佳答案
计时器只是一个延迟的函数调用。因此,为您的函数命名,您就可以“手动调用它:”
var typingTimer; //timer identifier
var doneTypingInterval = 2000; //time in ms, 2 second for example
$('textarea').on('input', function () {
// Clear timer
clearTimeout(typingTimer);
// Set new timer to save form, passing current repeater item to Save method
var parent = $(this).closest('.my-repeater-section');
function callback() {
saveForm(parent);
}
typingTimer = setTimeout(callback, doneTypingInterval);
// call it manually like usual:
// callback();
});
关于javascript - 如何在 JavaScript 中立即手动运行 setTimeout 计时器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13804828/