jiefancis / blogs

个人博客,学习笔记(issues)
1 stars 0 forks source link

Vue源码之nextTick解读 #16

Open jiefancis opened 3 years ago

jiefancis commented 3 years ago

nextTick的用法

nextTick实现

var pending = false,
        callbacks = [];

    var timerFunc;

    function flushQueue(){
        let copies = callbacks.slice()
        callbacks.length = 0;
        for(let i = 0; i < copies.length; i++) {
            copies[i]()
        }
    }

    if(typeof Promise !== undefined) {
        let p = Promise.resolve()
        timerFunc = function(){
            p.then(flushQueue)
        }
    } else if(typeof MutationObserver !== undefined) {
        let counter = 1;
        let textNode = document.createTextNode(counter)
        var oberser  = new MutationObserver(flushQueue)
        observer.observe(textNode)

        timerFunc = function(){
            couter = couter + 1;
            textNode.data = counter
        }
    } else if (typeof setImmediate !== undefined) {
        timerFunc = setImmediate(flushQueue)
    } else {
        timerFunc = setTimeout(flushQueue)
    }

    function nextTick(cb, ctx) {
        let _resolve;

        callbacks.push(() => {
            if(cb) {
                cb.call(ctx)
            } else if(_resolve) {
                _resolve(ctx)
            }
        })
        if(!pending) {
            pending = true;
            timerFunc()
        }
        if(!cb && typeof Promise !== undefined) {
            return new Promise((resolve, reject) => {
                _resolve = resolve
            })
        }
    }

    console.log('start')
    nextTick().then(res => {
        console.log('nexttick--empty-callback--then')
    })

    nextTick(() => {
        console.log('nextTick--function')
    })
    console.log('end')