如何實現中文防抖markdown
防抖:動做綁定事件,動做發生後必定時間後觸發事件,在這段時間內,若是該動做又發生,則從新等待必定時間再觸發事件。 防抖的簡單封裝:閉包
function debounce(fn,delay) {
// timer在閉包中,
let timer = null;
return function () {
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(() => {
fn.call(this, arguments);
timer = null;
}, delay);
};
}
複製代碼
在輸入框中使用防抖測試
const userName = document.getElementById('username');
userName.addEventListener('keyup', debounce(function() {
console.log(this.value);
}, 1000));
複製代碼
上面這種封裝和用法只能適用input輸入非中文內容。若是咱們在輸入中文的時候就會有一些問題,尚未肯定中文內容,可是定時器已經到時間了。就會觸發後續的操做。this
針對輸入中文字符實現防抖spa
function debounce(fn, delay) {
let timer = null;
return function(e) {
if (e.target.composing) {
return;
}
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(() => {
fn.call(this, arguments);
timer = null;
}, delay);
};
}
function compositionStart(e) {
e.target.composing = true;
}
function compositionEnd(e) {
e.target.composing = false;
const event = document.createEvent('HTMLEvents');
event.initEvent('input');
e.target.dispatchEvent(event);
}
複製代碼
測試中文防抖code
const userName = document.getElementById('username');
userName.addEventListener('keyup', debounce(function(e){
console.log(this.value);
}, 2000));
userName.addEventListener('compositionstart', compositionStart);
userName.addEventListener('compositionend', compositionEnd);
複製代碼
提到防抖,咱們就不得不想起節流,orm
節流: 動做綁定事件,動做發生後一段時間後觸發事件,在這段時間內,若是動做又發生,則無視該動做,直到事件執行完後,才能從新觸發。 防抖的簡單封裝:事件
function throttle(fn, delay) {
let timer = null;
return function () {
if (timer) {
return;
}
timer = setTimeout(() => {
fn.call(this, arguments);
timer = null;
}, delay);
};
}
```/
複製代碼