Skip to content

Commit

Permalink
Refactor: don't poll data in background tabs
Browse files Browse the repository at this point in the history
  • Loading branch information
katspaugh committed Feb 15, 2024
1 parent ffd511f commit 00bcd0c
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 5 deletions.
8 changes: 5 additions & 3 deletions src/hooks/__tests__/useIntervalCounter.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { act, renderHook } from '@testing-library/react'
import useIntervalCounter from '../useIntervalCounter'

global.requestAnimationFrame = (callback: any) => setTimeout(callback, 0)

describe('useIntervalCounter', () => {
beforeAll(() => {
jest.useFakeTimers()
Expand All @@ -13,13 +15,13 @@ describe('useIntervalCounter', () => {
expect(result.current[1]).toBeInstanceOf(Function)

act(() => {
jest.advanceTimersByTime(100)
jest.advanceTimersByTime(200)
})

expect(result.current[0]).toBe(1)

act(() => {
jest.advanceTimersByTime(100)
jest.advanceTimersByTime(200)
})

expect(result.current[0]).toBe(2)
Expand All @@ -29,7 +31,7 @@ describe('useIntervalCounter', () => {
const { result } = renderHook(() => useIntervalCounter(100))

act(() => {
jest.advanceTimersByTime(100)
jest.advanceTimersByTime(200)
})

expect(result.current[0]).toBe(1)
Expand Down
15 changes: 13 additions & 2 deletions src/hooks/useIntervalCounter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,19 @@ const useIntervalCounter = (interval: number): [number, () => void] => {
}, [setCounter])

useEffect(() => {
const timerId = setTimeout(() => setCounter(counter + 1), interval)
return () => clearTimeout(timerId)
let reqFrameId: number
const timerId = setTimeout(() => {
// requestAnimationFrame prevents the timer from ticking in a background tab
reqFrameId = requestAnimationFrame(() => {
setCounter(counter + 1)
})
}, interval)
return () => {
clearTimeout(timerId)
if (reqFrameId) {
cancelAnimationFrame(reqFrameId)
}
}
}, [counter, interval])

return [counter, resetCounter]
Expand Down

0 comments on commit 00bcd0c

Please sign in to comment.