2 回答
TA贡献1807条经验 获得超9个赞
您可以为输入提供一个自动保存时间戳,然后检查它是否已经过去,而不是试图让超时彼此重叠。
let auto_save_timer = null;
$('input.auto-save').on('keyup paste', function() {
this.setAttribute('data-auto-save-timeout', (new Date()).getTime() + 3000); //set save time
if (!auto_save_timer) {
auto_save_timer = setInterval(function() {
let $inputs = $('input[data-auto-save-timeout]');
if ($inputs.length) {
$inputs.each(function() {
if ((new Date()).getTime() - this.attributes['data-auto-save-timeout'].value >= 0) {
this.removeAttribute('data-auto-save-timeout');
your_save_function(this);
}
});
} else {
clearInterval(auto_save_timer); //stops the timer
auto_save_timer = null; //for checking if the timer is active,
//clearInterval() doesn't make it false
//this prevents multiple timers from overlapping
}
}, 1000);
}
});
https://jsfiddle.net/sjmdqhgu/
TA贡献1848条经验 获得超2个赞
您可以为输入提供一个自动保存时间戳,然后检查它是否已经过去,而不是试图让超时彼此重叠。
let auto_save_timer = null;
$('input.auto-save').on('keyup paste', function() {
this.setAttribute('data-auto-save-timeout', (new Date()).getTime() + 3000); //set save time
if (!auto_save_timer) {
auto_save_timer = setInterval(function() {
let $inputs = $('input[data-auto-save-timeout]');
if ($inputs.length) {
$inputs.each(function() {
if ((new Date()).getTime() - this.attributes['data-auto-save-timeout'].value >= 0) {
this.removeAttribute('data-auto-save-timeout');
your_save_function(this);
}
});
} else {
clearInterval(auto_save_timer); //stops the timer
auto_save_timer = null; //for checking if the timer is active,
//clearInterval() doesn't make it false
//this prevents multiple timers from overlapping
}
}, 1000);
}
});
https://jsfiddle.net/sjmdqhgu/
添加回答
举报