如何像在 c 中那样在 JavaScript 中创建一个静态变量? (避免重新初始化变量)
How to make a static variable in JavaScript like we do in c ? ( to avoid re-initialization of the variable)
我在 https://www.youtube.com/watch?v=cjIswDCKgu0&t=429s YouTube 上看过这个视频;
我只是想做一个简单的去抖功能。但是此代码无法按预期在我的设备上运行。请帮忙。
<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="true">
<div class="snippet-code">
<pre><code>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);
});
我在 https://www.youtube.com/watch?v=cjIswDCKgu0&t=429s YouTube 上看过这个视频;
我只是想做一个简单的去抖功能。但是此代码无法按预期在我的设备上运行。请帮忙。
<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="true">
<div class="snippet-code">
<pre><code>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);
});