Skip to content

Commit

Permalink
Fix implementation to only clear when asked to
Browse files Browse the repository at this point in the history
Signed-off-by: Sebastian Malton <sebastian@malton.name>
  • Loading branch information
Nokel81 committed Jul 24, 2023
1 parent 049883c commit b084704
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 23 deletions.
32 changes: 11 additions & 21 deletions src/now.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,13 @@ const tickers: {
[interval: string]: IResource<number>
} = {}

let synchronized = true

/**
* Turns of the synchronization of {@link now} for unit testing so that tests don't share state between them
*/
export function desynchronizeNowForTests() {
synchronized = false
export function clearTimers() {
for (const key in tickers) {
if (tickers.hasOwnProperty(key)) {
tickers[key].dispose()
delete tickers[key]
}
}
}

/**
Expand Down Expand Up @@ -46,21 +46,11 @@ export function now(interval: number | "frame" = 1000) {
return Date.now()
}

if (!synchronized) {
if (typeof interval === "number") {
return createIntervalTicker(interval).current()
}

return createAnimationFrameTicker().current()
if (!tickers[interval]) {
if (typeof interval === "number") tickers[interval] = createIntervalTicker(interval)
else tickers[interval] = createAnimationFrameTicker()
}

const timer = tickers[interval]
? tickers[interval]
: typeof interval === "number"
? createIntervalTicker(interval)
: createAnimationFrameTicker()

return timer.current()
return tickers[interval].current()
}

function createIntervalTicker(interval: number): IResource<number> {
Expand Down
6 changes: 4 additions & 2 deletions test/now.js
Original file line number Diff line number Diff line change
Expand Up @@ -62,8 +62,6 @@ describe("given desynchronization is enabled", () => {
jest.useFakeTimers("modern")
jest.setSystemTime(new Date("2015-10-21T07:28:00Z"))

utils.desynchronizeNowForTests()

const someComputed = mobx.computed(() => {
const currentTimestamp = utils.now(1000)

Expand All @@ -79,6 +77,10 @@ describe("given desynchronization is enabled", () => {
)
})

afterEach(() => {
utils.clearTimers()
})

it("given time passes, works", () => {
jest.advanceTimersByTime(1000)

Expand Down

0 comments on commit b084704

Please sign in to comment.