gpt4 book ai didi

javascript - 将 Throttle-Debounce 与 addEventListener 结合使用

转载 作者:行者123 更新时间:2023-12-05 08:01:27 24 4
gpt4 key购买 nike

我在移动网站上使用 deviceorientation,但我不想捕捉每一个 Action 。我只想要每秒 1 个,所以我正在尝试使用 throttle-debounce 插件。

我原来的工作代码是这样的......

window.addEventListener(
'deviceorientation',
function (event) {
tilt([event.alpha, event.beta, event.gamma]);
},
true);

...但是当我像这样添加 throttle ...

window.addEventListener(
'deviceorientation',
$.throttle(
1000,
function (event){
tilt([event.alpha, event.beta, event.gamma]);
}),
true);

...我得到一个...

Uncaught TypeError: Object function ( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init( selector, context, rootjQuery );
} has no method 'throttle'

我猜我弄错了语法,但我已经尝试了几个变体,但还是不太明白。帮忙?

如果有人有更好的方法在没有插件的情况下做同样的事情:)

最佳答案

  • 不需要 jquery 进行简单的反跳
  • 这里是普通 purejs 去抖功能的简单示例
let timeoutId;
window.addEventListener(
'deviceorientation',
function () {
// you clear your time out each event
clearTimeout(timeoutId)
// if no event during 1s, then run your function
timeoutId = setTimeout(() => {
// perform function after delay
}, 1000)
};

关于javascript - 将 Throttle-Debounce 与 addEventListener 结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14149084/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com