Skip to content

Commit

Permalink
Merge pull request #163 from namoscato/memory
Browse files Browse the repository at this point in the history
Fix memory leak
  • Loading branch information
nmn authored Jun 10, 2022
2 parents 02ebc5f + ba0f600 commit 0d7c0f9
Showing 1 changed file with 16 additions and 26 deletions.
42 changes: 16 additions & 26 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
// @flow

import * as React from 'react'
import { useCallback, useEffect, useState } from 'react'
import defaultFormatter from './defaultFormatter'
import { useEffect, useState } from 'react'
import dateParser from './dateParser'
import defaultFormatter from './defaultFormatter'

export type Unit =
| 'second'
Expand Down Expand Up @@ -65,22 +65,20 @@ export default function TimeAgo({
minPeriod = 0,
maxPeriod = WEEK,
title,
now = () => Date.now(),
now = Date.now,
...passDownProps
}: Props): null | React.MixedElement {
const forceUpdate = useUpdate()
const [timeNow, setTimeNow] = useState(now())
useEffect(() => {
if (!live) {
return
}
let timeoutId
const tick = (refresh: ?boolean): void => {
const tick = (): number => {
const then = dateParser(date).valueOf()
if (!then) {
console.warn('[react-timeago] Invalid Date provided')
return
return 0
}
const timeNow = now()
const seconds = Math.round(Math.abs(timeNow - then) / 1000)

const unboundPeriod =
Expand All @@ -98,28 +96,27 @@ export default function TimeAgo({
)

if (period) {
if (timeoutId) {
clearTimeout(timeoutId)
}
timeoutId = setTimeout(tick, period)
}
if (!refresh) {
forceUpdate()
return setTimeout(() => {
setTimeNow(now())
}, period)
}

return 0
}
tick(true)
const timeoutId = tick()
return () => {
clearTimeout(timeoutId)
if (timeoutId) {
clearTimeout(timeoutId)
}
}
}, [date, forceUpdate, live, maxPeriod, minPeriod, now])
}, [date, live, maxPeriod, minPeriod, now, timeNow])

const Komponent = component
const then = dateParser(date).valueOf()
if (!then) {
return null
}

const timeNow = now()
const seconds = Math.round(Math.abs(timeNow - then) / 1000)
const suffix = then < timeNow ? 'ago' : 'from now'

Expand Down Expand Up @@ -158,10 +155,3 @@ export default function TimeAgo({
</Komponent>
)
}

function useUpdate(): () => void {
const [_, setCount] = useState(0)
return useCallback(() => {
setCount((num) => num + 1)
}, [])
}

0 comments on commit 0d7c0f9

Please sign in to comment.