如何在n秒后停用MutationsObserver?

时间:2016-10-29 17:43:37

标签: javascript ecmascript-6 generator observable

我正在写一个generator函数(用co库中的包装器包裹,允许我yieldPromises,la {{1} })。

脚本在DOM节点上调用async await,然后等待使用MutationObserver API显示的弹出窗口,我已将其包含在button.click()中:

promise

在调用者中,即const startDOMObservable = (domNode) => { return new Promise((resolve) => { let observer = new MutationObserver(function (mutations, obs) { mutations.forEach(function (mutation) { obs.disconnect() resolve(mutations, obs) }) }) observer.observe(targetNode, { childList: true }) }) } ,我将此函数称为:

generator

ETA:这个生成器/承诺模式可能看起来有点奇怪,但它有效(到目前为止,我认为).h / t到David Walsh blog来写它)< / p>

由于调用document.querySelector('.the_button').click() const mutations = yield startDOMObservable( document.querySelector('.parent_of_popup') ) 的生成器函数是startDOMObservable,如何处理没有发生突变的实例?如果发生这种情况,我希望yieldresolve承诺与适当的消息。

1 个答案:

答案 0 :(得分:1)

您需要在n秒后添加超时并断开观察者身份,然后解决或拒绝

const startDOMObservable = (domNode, secs) => {

    return new Promise((resolve, reject) => {

        let observer = new MutationObserver(function(mutations, obs) {
            obs.disconnect();
            clearTimeout( timeout );
            resolve(mutations, obs);
        });

        observer.observe(domNode, {
            childList: true
        });

        let timeout = setTimeout(() => {
            observer.disconnect();
            reject('Nothing happened ?');
        }, secs * 1000);
    })
}

然后

const mutations = yield startDOMObservable(
   document.querySelector('.parent_of_popup'), 2 // <- seconds to wait
)

document.querySelector('.the_button').click()