最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How can I throttle a ResizeObserver? - Stack Overflow

programmeradmin3浏览0评论

I currently use a ResizeObserver to watch the size of an element but I was thinking of using a throttle (lodash's throttle) to increase the performance of it.

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

let imageToWatch = document.querySelector('.image');
myResize.observe(imageToWatch);

is there a way I can throttle this? Would the throttle just be on the logic inside myResize? I assume I can't throttle the observe portion of this though.

I currently use a ResizeObserver to watch the size of an element but I was thinking of using a throttle (lodash's throttle) to increase the performance of it.

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

let imageToWatch = document.querySelector('.image');
myResize.observe(imageToWatch);

is there a way I can throttle this? Would the throttle just be on the logic inside myResize? I assume I can't throttle the observe portion of this though.

Share Improve this question edited Oct 6, 2021 at 19:16 zero298 26.9k10 gold badges79 silver badges106 bronze badges asked Oct 6, 2021 at 16:58 user17091428user17091428 1
  • 1 Please don't deface your posts. I'm not sure what your last edit was trying to do. – zero298 Commented Oct 6, 2021 at 19:16
Add a comment  | 

1 Answer 1

Reset to default 22

The behaviour of ResizeObserver could only be modified if you would recreate that constructor. It will indeed be simpler to just throttle the callback function that you pass to that constructor.

To demo this, here is a textarea element, which by default can be resized interactively. The handler will change the background color of the textarea, but only if 1 second passed after the last event. For this purpose the handler is wrapped in a call to 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);
<textarea></textarea>

发布评论

评论列表(0)

  1. 暂无评论