Skip to content

Commit

Permalink
feat: immediate option, return start function
Browse files Browse the repository at this point in the history
  • Loading branch information
okxiaoliang4 committed Feb 20, 2023
1 parent 5452eb1 commit 4f91205
Showing 1 changed file with 22 additions and 3 deletions.
25 changes: 22 additions & 3 deletions packages/core/usePerformanceObserver/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,14 @@ import { useSupported } from '../useSupported'
import type { ConfigurableWindow } from '../_configurable'
import { defaultWindow } from '../_configurable'

export type UsePerformanceObserverOptions = PerformanceObserverInit & ConfigurableWindow
export type UsePerformanceObserverOptions = PerformanceObserverInit & ConfigurableWindow & {
/**
* Start the observer immediate.
*
* @default true
*/
immediate?: boolean
}

/**
* Observe performance metrics.
Expand All @@ -14,22 +21,34 @@ export type UsePerformanceObserverOptions = PerformanceObserverInit & Configurab
export function usePerformanceObserver(options: UsePerformanceObserverOptions, callback: PerformanceObserverCallback) {
const {
window = defaultWindow,
immediate = true,
...performanceOptions
} = options

const isSupported = useSupported(() => window && 'PerformanceObserver' in window)

const observer = new PerformanceObserver(callback)
observer.observe(performanceOptions)
let observer: PerformanceObserver | undefined

const stop = () => {
observer?.disconnect()
}

const start = () => {
if (isSupported.value) {
stop()
observer = new PerformanceObserver(callback)
observer.observe(performanceOptions)
}
}

tryOnScopeDispose(stop)

if (immediate)
start()

return {
isSupported,
start,
stop,
}
}

0 comments on commit 4f91205

Please sign in to comment.