$nextTick 、setTimeout 原理与区别

编程入门 行业动态 更新时间:2024-10-08 04:33:18

$nextTick 、setTimeout <a href=https://www.elefans.com/category/jswz/34/1770123.html style=原理与区别"/>

$nextTick 、setTimeout 原理与区别

$nextTick实现原理

  1. 主要利用 Promise.resolve()

  2. vue2.5+后,nextTict源码由next-tick.ts维护,文件源码路径vue/src/core/util/next-tick.ts,官网链接

/* globals MutationObserver */import { noop } from 'shared/util'
import { handleError } from './error'
import { isIE, isIOS, isNative } from './env'export let isUsingMicroTask = falseconst callbacks: Array<Function> = []
let pending = falsefunction flushCallbacks() {pending = falseconst copies = callbacks.slice(0)callbacks.length = 0for (let i = 0; i < copies.length; i++) {copies[i]()}
}// Here we have async deferring wrappers using microtasks.
// In 2.5 we used (macro) tasks (in combination with microtasks).
// However, it has subtle problems when state is changed right before repaint
// (e.g. #6813, out-in transitions).
// Also, using (macro) tasks in event handler would cause some weird behaviors
// that cannot be circumvented (e.g. #7109, #7153, #7546, #7834, #8109).
// So we now use microtasks everywhere, again.
// A major drawback of this tradeoff is that there are some scenarios
// where microtasks have too high a priority and fire in between supposedly
// sequential events (e.g. #4521, #6690, which have workarounds)
// or even between bubbling of the same event (#6566).
let timerFunc// The nextTick behavior leverages the microtask queue, which can be accessed
// via either native Promise.then or MutationObserver.
// MutationObserver has wider support, however it is seriously bugged in
// UIWebView in iOS >= 9.3.3 when triggered in touch event handlers. It
// completely stops working after triggering a few times... so, if native
// Promise is available, we will use it:
/* istanbul ignore next, $flow-disable-line */
if (typeof Promise !== 'undefined' && isNative(Promise)) {const p = Promise.resolve()timerFunc = () => {p.then(flushCallbacks)// In problematic UIWebViews, Promise.then doesn't completely break, but// it can get stuck in a weird state where callbacks are pushed into the// microtask queue but the queue isn't being flushed, until the browser// needs to do some other work, e.g. handle a timer. Therefore we can// "force" the microtask queue to be flushed by adding an empty timer.if (isIOS) setTimeout(noop)}isUsingMicroTask = true
} else if (!isIE &&typeof MutationObserver !== 'undefined' &&(isNative(MutationObserver) ||// PhantomJS and iOS 7.xMutationObserver.toString() === '[object MutationObserverConstructor]')
) {// Use MutationObserver where native Promise is not available,// e.g. PhantomJS, iOS7, Android 4.4// (#6466 MutationObserver is unreliable in IE11)let counter = 1const observer = new MutationObserver(flushCallbacks)const textNode = document.createTextNode(String(counter))observer.observe(textNode, {characterData: true})timerFunc = () => {counter = (counter + 1) % 2textNode.data = String(counter)}isUsingMicroTask = true
} else if (typeof setImmediate !== 'undefined' && isNative(setImmediate)) {// Fallback to setImmediate.// Technically it leverages the (macro) task queue,// but it is still a better choice than setTimeout.timerFunc = () => {setImmediate(flushCallbacks)}
} else {// Fallback to setTimeout.timerFunc = () => {setTimeout(flushCallbacks, 0)}
}export function nextTick(): Promise<void>
export function nextTick<T>(this: T, cb: (this: T, ...args: any[]) => any): void
export function nextTick<T>(cb: (this: T, ...args: any[]) => any, ctx: T): void
/*** @internal*/
export function nextTick(cb?: (...args: any[]) => any, ctx?: object) {let _resolvecallbacks.push(() => {if (cb) {try {cb.call(ctx)} catch (e: any) {handleError(e, ctx, 'nextTick')}} else if (_resolve) {_resolve(ctx)}})if (!pending) {pending = truetimerFunc()}// $flow-disable-lineif (!cb && typeof Promise !== 'undefined') {return new Promise(resolve => {_resolve = resolve})}
}
  1. nextTick源码解读:
  • cb是 传入的回调,被push到callbacks中,等待执行。
  • pending是一个锁,防止后续的nextTick重复执行timerFunc()timerFunc()内部会创建一个微任务或宏任务,等待所有的nextTick同步执行完成后,再去执行callbacks中的回调。
  • 要是没有cb,传入的是Promise,则返回Promise_resolve被调用时,执行进入then
  • 根据不同兼容要求,创建合适的timerFunc,优先级Promise.resolve()>MutationObserver>setImmediate>setTimeout
  • 不管哪种timerFunc,其创建完后,都会执行flushCallbacks
  • flushCallbacks主要是执行callbacks中的回调。
  1. vue的异步更新流程

(1) 数据改变时,会触发watcher.update

  • 源码路径vue/src/core/observer/watcher.ts
  • 源码链接.ts
/*** Subscriber interface.* Will be called when a dependency changes.*/update() {/* istanbul ignore else */if (this.lazy) {this.dirty = true} else if (this.sync) {this.run()} else {queueWatcher(this)}}

(2) 调用queueWatcher函数,将watcherpush到queue中,再将queue中的watcher循环run更新,同时resetSchedulerState重置状态,等待下一轮更新。

  • 源码路径vue/src/core/observer/scheduler.ts
  • 源码链接.ts

queueWatcher函数中:
每个watcher 都有自己的id,先判断has[id] != null,是为去掉重复的watcher,保证唯一性
watcherpush到queue中,等待执行
waiting是为了防止重复执行nextTick
flushSchedulerQueue函数作为回调,传入nextTick,而此刻flushSchedulerQueue还未执行,仅仅只是回调传入。这时用户可能也会调用nextTick,则这种情况下callbacksflushSchedulerQueue, 用户的nextTick回调,当所有同步任务执行完成,才开始执行callbacks里面的回调。

flushSchedulerQueue函数中:
将刚刚加入queue中的watcher循环run更新,resetSchedulerState()重置状态,等待下一轮异步更新。

所以,页面更新逻辑 先执行,其次执行用户的nextTick回调。(所以,nextTick可以获取到更新后的DOM,一般用于 视图更新后,基于新的视图进行操作)

import type Watcher from './watcher'
import config from '../config'
import Dep, { cleanupDeps } from './dep'
import { callHook, activateChildComponent } from '../instance/lifecycle'import { warn, nextTick, devtools, inBrowser, isIE } from '../util/index'
import type { Component } from 'types/component'export const MAX_UPDATE_COUNT = 100const queue: Array<Watcher> = []
const activatedChildren: Array<Component> = []
let has: { [key: number]: true | undefined | null } = {}
let circular: { [key: number]: number } = {}
let waiting = false
let flushing = false
let index = 0/*** Reset the scheduler's state.*/
function resetSchedulerState() {index = queue.length = activatedChildren.length = 0has = {}if (__DEV__) {circular = {}}waiting = flushing = false
}// Async edge case #6566 requires saving the timestamp when event listeners are
// attached. However, calling performance.now() has a perf overhead especially
// if the page has thousands of event listeners. Instead, we take a timestamp
// every time the scheduler flushes and use that for all event listeners
// attached during that flush.
export let currentFlushTimestamp = 0// Async edge case fix requires storing an event listener's attach timestamp.
let getNow: () => number = Date.now// Determine what event timestamp the browser is using. Annoyingly, the
// timestamp can either be hi-res (relative to page load) or low-res
// (relative to UNIX epoch), so in order to compare time we have to use the
// same timestamp type when saving the flush timestamp.
// All IE versions use low-res event timestamps, and have problematic clock
// implementations (#9632)
if (inBrowser && !isIE) {const performance = window.performanceif (performance &&typeof performance.now === 'function' &&getNow() > document.createEvent('Event').timeStamp) {// if the event timestamp, although evaluated AFTER the Date.now(), is// smaller than it, it means the event is using a hi-res timestamp,// and we need to use the hi-res version for event listener timestamps as// well.getNow = () => performance.now()}
}const sortCompareFn = (a: Watcher, b: Watcher): number => {if (a.post) {if (!b.post) return 1} else if (b.post) {return -1}return a.id - b.id
}/*** Flush both queues and run the watchers.*/
function flushSchedulerQueue() {currentFlushTimestamp = getNow()flushing = truelet watcher, id// Sort queue before flush.// This ensures that:// 1. Components are updated from parent to child. (because parent is always//    created before the child)// 2. A component's user watchers are run before its render watcher (because//    user watchers are created before the render watcher)// 3. If a component is destroyed during a parent component's watcher run,//    its watchers can be skipped.queue.sort(sortCompareFn)// do not cache length because more watchers might be pushed// as we run existing watchersfor (index = 0; index < queue.length; index++) {watcher = queue[index]if (watcher.before) {watcher.before()}id = watcher.idhas[id] = nullwatcher.run()// in dev build, check and stop circular updates.if (__DEV__ && has[id] != null) {circular[id] = (circular[id] || 0) + 1if (circular[id] > MAX_UPDATE_COUNT) {warn('You may have an infinite update loop ' +(watcher.user? `in watcher with expression "${watcher.expression}"`: `in a component render function.`),watcher.vm)break}}}// keep copies of post queues before resetting stateconst activatedQueue = activatedChildren.slice()const updatedQueue = queue.slice()resetSchedulerState()// call component updated and activated hookscallActivatedHooks(activatedQueue)callUpdatedHooks(updatedQueue)cleanupDeps()// devtool hook/* istanbul ignore if */if (devtools && config.devtools) {devtools.emit('flush')}
}function callUpdatedHooks(queue: Watcher[]) {let i = queue.lengthwhile (i--) {const watcher = queue[i]const vm = watcher.vmif (vm && vm._watcher === watcher && vm._isMounted && !vm._isDestroyed) {callHook(vm, 'updated')}}
}/*** Queue a kept-alive component that was activated during patch.* The queue will be processed after the entire tree has been patched.*/
export function queueActivatedComponent(vm: Component) {// setting _inactive to false here so that a render function can// rely on checking whether it's in an inactive tree (e.g. router-view)vm._inactive = falseactivatedChildren.push(vm)
}function callActivatedHooks(queue) {for (let i = 0; i < queue.length; i++) {queue[i]._inactive = trueactivateChildComponent(queue[i], true /* true */)}
}/*** Push a watcher into the watcher queue.* Jobs with duplicate IDs will be skipped unless it's* pushed when the queue is being flushed.*/
export function queueWatcher(watcher: Watcher) {const id = watcher.idif (has[id] != null) {return}if (watcher === Dep.target && watcher.noRecurse) {return}has[id] = trueif (!flushing) {queue.push(watcher)} else {// if already flushing, splice the watcher based on its id// if already past its id, it will be run next immediately.let i = queue.length - 1while (i > index && queue[i].id > watcher.id) {i--}queue.splice(i + 1, 0, watcher)}// queue the flushif (!waiting) {waiting = trueif (__DEV__ && !config.async) {flushSchedulerQueue()return}nextTick(flushSchedulerQueue)}
}

$nextTick & setTimeout 区别

知道$nextTick是利用 Promise.resolve()实现的,则$nextTick & setTimeout的区别本质上是事件循环(Event Loop)中微任务和宏任务的区别。

$nextTick:在下次 DOM 更新循环结束之后 执行延迟回调;一般使用在DOM操作上。
setTimeout:只是个 延迟回调;与DOM操作无关。

优先级:nextTick > setTimeout(微任务 > 宏任务)

宏任务:script(整体代码)、setTimout、setInterval、setImmediate(node.js环境)、I/O、UI交互事件
微任务:new promise().then(回调)、MutationObserver(html5新特新)、Object.observe(已废弃)、process.nextTick(node环境)

参考


更多推荐

$nextTick 、setTimeout 原理与区别

本文发布于:2024-02-07 10:38:05,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1756258.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:原理   区别   nextTick   setTimeout

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!