Open jiefancis opened 3 years ago
在下次 DOM 更新循环结束之后执行延迟回调。在修改数据之后立即使用这个方法,获取更新后的 DOM。
nextTick().then() 不传入回调,nextTick函数将会返回一个promise函数。 nextTick(cb)
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')
nextTick的用法
在下次 DOM 更新循环结束之后执行延迟回调。在修改数据之后立即使用这个方法,获取更新后的 DOM。
nextTick如何实现回调延迟执行?
nextTick实现