我在https://www.youtube.com/watch?v=cjIswDCKgu0&t=429s YouTube 上觀看了這個視頻;
我只是想做一個簡單的去抖動功能。但是此代碼無法按預期在我的設備上運行。請幫忙。
let debounceTimes = 0;
// this code does not work as intended
let timeout; // if I make it global it works just fine
// but I don't want to do that for obvious reasons
function debounce(cb, delay = 100) {
// let timeout; // this is being reinitialized
// only if I could do something like this
// static timeout;
// to avoid re-initializing the variable
// return (...args) => {
clearTimeout(timeout);
timeout = setTimeout(() => {
cb();
}, delay);
// }
}
window.addEventListener("mousemove", () => {
// console.log("hello");
// document.getElementById("debounce").innerText ;
debounce(
() => {
debounceTimes ;
document.getElementById("debounce").innerText = String(debounceTimes);
}, 100);
});
Run code snippetHide resultsExpand snippet
uj5u.com熱心網友回復:
要呼叫靜態方法,我們不需要創建類的實體或物件。JavaScript 中的靜態變數:我們使用 static 關鍵字將變數設為靜態,就像使用 const 關鍵字定義常量變數一樣。它是在運行時設定的,這種型別的變數用作全域變數。
uj5u.com熱心網友回復:
在這個例子中,這是不可能的,因為當事件被觸發時,它只是運行在debounce內部創建變數的函式。為避免重新初始化變數,您可以:
在全域范圍內創建變數
創建另一個回傳去抖動函式的函式(因此超時隱藏在函式范圍內)
let debounceTimes = 0;
function getDebounce() {
let timeout;
function debounce(cb, delay = 100) {
clearTimeout(timeout);
timeout = setTimeout(() => {
cb();
}, delay);
}
return debounce;
}
const debounce = getDebounce();
window.addEventListener('mousemove', () => {
debounce(() => {
debounceTimes ;
document.getElementById('debounce').innerText = String(debounceTimes);
}, 100);
});
uj5u.com熱心網友回復:
如我所見,您沒有在去抖功能中使用超時變數,然后嘗試將其作為去抖功能的引數...
let debounceTimes = 0;
// this code does not work as intended
// if I make it global it works just fine
// but I don't want to do that for obvious reasons
function debounce(timeout, cb, delay = 100) {
// let timeout; // this is being reinitialized
// only if I could do something like this
// static timeout;
// to avoid re-initializing the variable
// return (...args) => {
clearTimeout(timeout);
timeout = setTimeout(() => {
cb();
}, delay);
// }
}
window.addEventListener("mousemove", () => {
// console.log("hello");
// document.getElementById("debounce").innerText ;
debounce(
() => {
debounceTimes ;
document.getElementById("debounce").innerText = String(debounceTimes);
}, 100);
});
Run code snippetHide resultsExpand snippet
uj5u.com熱心網友回復:
我最終用靜態方法和變數創建了一個類,因為它類似于 c 的做事方式。但我更喜歡@Tomasz Staszkiewicz 的回答。他在函式內部創建了另一個函式來實作這一點。
class ignoreInput {
static timeout;
static debounce (cb, delay = 100) {
clearTimeout(this.timeout);
this.timeout = setTimeout(() => {
cb();
}
, delay);
}
static throttle (cb, delay = 100) {
// some code
}
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/475647.html
標籤:javascript 表现 优化 静止的 去抖
