Skip to content

Commit

Permalink
🐎 hasValidContext() is slow, cache it
Browse files Browse the repository at this point in the history
  • Loading branch information
astoilkov committed Jan 16, 2024
1 parent dc49df2 commit d9ab933
Showing 1 changed file with 18 additions and 11 deletions.
29 changes: 18 additions & 11 deletions src/isTimeToYield.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,36 +3,43 @@ import hasValidContext from './utils/hasValidContext'
import SchedulingPriority from './SchedulingPriority'

// #performance
// calling `isTimeToYield()` thousand of times is slow. `lastCall` helps to run logic inside of
// `isTimeToYield()` at most 1 per millisecond.
let lastCallTime = 0
let lastResult = false
// calling `isTimeToYield()` thousand of times is slow. `cache` helps isTimeToYield() run faster
const cache = {
lastCallTime: 0,
lastResult: false,
hasValidContext: undefined as boolean | undefined,
}

/**
* Determines if it's time to call `yieldControl()`.
*/
export default function isTimeToYield(priority: SchedulingPriority = 'user-visible'): boolean {
if (!hasValidContext()) {
if (cache.hasValidContext === undefined) {
cache.hasValidContext = hasValidContext()
}

if (!cache.hasValidContext) {
return false
}

// #performance, `performance.now()` is around 40% slower. also `Date.now()` is accurate enough
// for our use case
const now = Date.now()

if (!lastResult && now - lastCallTime === 0) {
return lastResult
// #performance, call the slow logic of `isTimeToYield` at most 1 per millisecond
if (!cache.lastResult && now - cache.lastCallTime === 0) {
return cache.lastResult
}

lastCallTime = now
lastResult =
cache.lastCallTime = now
cache.lastResult =
now >= calculateDeadline(priority) || navigator.scheduling?.isInputPending?.() === true

if (lastResult) {
if (cache.lastResult) {
schedulingState.isThisFrameBudgetSpent = true
}

return lastResult
return cache.lastResult
}

function calculateDeadline(priority: SchedulingPriority): number {
Expand Down

0 comments on commit d9ab933

Please sign in to comment.