我应该如何结合防抖和MutationObserver

时间:2019-01-03 06:54:37

标签: javascript mutation-observers debounce

我想知道何时停止调用突变。因此,我正在执行反跳操作。但是我的console.log('***** Debounced ****');从未被调用。

能否请您帮助我了解我在做什么错。

var target = document.body;
var observer = new MutationObserver(function(mutations) 
{
    mutations.forEach(function(mutation) 
        {
            for (var i = 0; i < mutation.addedNodes.length; i++) 
                {
                    var item = mutation.addedNodes[i];
                    console.log(item);
                    myCustomFunction
                }
        });
});         

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

var myCustomFunction = debounce(function() 
               {
                   console.log('*****Debounced ****');
                   //call some method do more work etc
                }, 500);

function debounce(func, wait, immediate) 
{
var timeout;
return function() {
    var context = this,
        args = arguments;
    var later = function() {
        timeout = null;
        if ( !immediate ) {
            func.apply(context, args);
        }
    };
    var callNow = immediate && !timeout;
    clearTimeout(timeout);
    timeout = setTimeout(later, wait || 1000);
    if ( callNow ) {
        func.apply(context, args);
    }
};
}

0 个答案:

没有答案