2 回答

TA貢獻(xiàn)1807條經(jīng)驗(yàn) 獲得超9個(gè)贊
您可以為輸入提供一個(gè)自動(dòng)保存時(shí)間戳,然后檢查它是否已經(jīng)過(guò)去,而不是試圖讓超時(shí)彼此重疊。
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貢獻(xiàn)1848條經(jīng)驗(yàn) 獲得超2個(gè)贊
您可以為輸入提供一個(gè)自動(dòng)保存時(shí)間戳,然后檢查它是否已經(jīng)過(guò)去,而不是試圖讓超時(shí)彼此重疊。
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/
添加回答
舉報(bào)