突变观察者发出 n 次变化,这使我的其他功能变慢有什么方法可以等待每次更改迭代然后继续?

问题描述

我有 1 个用作指令的突变观察者,

Mutation.ts:

const element = this.elementRef.nativeElement;

        this.changes = new MutationObserver((mutations: MutationRecord[]) => {
            mutations.forEach((mutation: MutationRecord) => this.domChange.emit(mutation));
        }
        );

        this.changes.observe(element,{
            childList: true,subtree: true
        });

组件 HTML :

<child-component (mutation)="mutate($event)"></child-component>

组件 TS:

mutate(event) {
if(searchKey) {
const elements = this.elem.nativeElement.querySelectorAll(`.${'highlight'}`);
      const instance = new Mark(elements);
      instance.mark(searchKey,options);
}
}

这个子组件加载了近 500 条记录,dom change 发出的次数太多,以至于我的 mutate(event) 函数无法一次处理所有这些。需要了解是否有一种方法可以在不冻结应用程序的情况下为每个请求突出显示

解决方法

退房:Performance of MutationObserver to detect nodes in entire DOM

 const queue = [];
    const mo = new MutationObserver(mutations => {
      if (!queue.length) requestAnimationFrame(process);
      queue.push(mutations);
    });
    function process() {
      for (const mutations of queue) {
        // ..........
      }
      queue.length = 0;
    }

这段代码运行良好。那篇文章中给出了很好的答案。谢谢。