如何限制 ResizeObserver?

8 javascript

我目前使用 ResizeObserver 来观察元素的大小,但我正在考虑使用节流阀(lodash 的节流阀)来提高它的性能。

const myResize = new ResizeObserver((entries) => {
    const el = document.querySelector('#foo');
    // get boundingRect and adjust height
});

let imageToWatch = document.querySelector('.image');
myResize.observe(imageToWatch);
Run Code Online (Sandbox Code Playgroud)

我有办法吗throttle?节流阀只是在内部逻辑上吗myResize?我想我无法限制observe这一部分。

tri*_*cot 16

ResizeObserver仅当您重新创建该构造函数时,才能修改 的行为。仅限制传递给该构造函数的回调函数确实会更简单。

为了演示这一点,这里有一个textarea元素,默认情况下可以交互式地调整其大小。处理程序将更改文本区域的背景颜色,但前提是在最后一个事件之后经过 1 秒。为此,处理程序被包装在对以下内容的调用中throttle(f, delay)

function throttle(f, delay) {
    let timer = 0;
    return function(...args) {
        clearTimeout(timer);
        timer = setTimeout(() => f.apply(this, args), delay);
    }
}

const myResize = new ResizeObserver(throttle((entries) => {
    entries[0].target.style.backgroundColor = 
        "#" + (Math.random() * 4096 | 0).toString(16);
}, 1000));

const elemToWatch = document.querySelector('textarea');
myResize.observe(elemToWatch);
Run Code Online (Sandbox Code Playgroud)
<textarea></textarea>
Run Code Online (Sandbox Code Playgroud)

  • 好答案。我只认为这种行为称为“debounce”而不是“throttle”。https://programmingwithmosh.com/javascript/javascript-throttle-and-debounce-patterns/ (13认同)
  • 谢谢你!!完美的 (2认同)