Skip to content

Commit

Permalink
Fix createPolled firing twice initially (fixes #632)
Browse files Browse the repository at this point in the history
  • Loading branch information
thetarnav committed Sep 8, 2024
1 parent 3f8dff7 commit 8dfd42d
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 7 deletions.
5 changes: 5 additions & 0 deletions .changeset/rich-worms-behave.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@solid-primitives/timer": patch
---

Fix createPolled firing twice initially (#632)
10 changes: 4 additions & 6 deletions packages/timer/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ import {
createEffect,
untrack,
Accessor,
createComputed,
SignalOptions,
createMemo,
} from "solid-js";
import { isServer } from "solid-js/web";

Expand Down Expand Up @@ -178,11 +178,9 @@ export function createPolled<T>(
if (isServer) {
return fn as Accessor<T>;
}
const [polled, setPolled] = createSignal(untrack(fn.bind(void 0, value)), options);
const update = () => setPolled(fn);
createTimer(update, timeout, setInterval);
createComputed(update);
return polled;
const memo = createMemo(() => createSignal(untrack(fn.bind(void 0, value)), options), options);
createTimer(() => memo()[1](fn), timeout, setInterval);
return () => memo()[0]();
}

/**
Expand Down
22 changes: 21 additions & 1 deletion packages/timer/test/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { batch, createRoot, createSignal } from "solid-js";
import { describe, test, expect, vi, beforeEach, afterAll, beforeAll } from "vitest";
import { createTimer } from "../src/index.js";
import { createPolled, createTimer } from "../src/index.js";

beforeAll(() => {
vi.useFakeTimers();
Expand Down Expand Up @@ -110,3 +110,23 @@ describe("createTimes", () => {
dispose();
});
});

describe("createPolled", () => {
test("fn called initially and after timeout", () => {
let n = 0
const {polled, dispose} = createRoot(dispose => ({
polled: createPolled(() => ++n, 100),
dispose,
}))
expect(polled()).toBe(1)

vi.advanceTimersByTime(100)
expect(polled()).toBe(2)

dispose()
expect(polled()).toBe(2)

vi.advanceTimersByTime(100)
expect(polled()).toBe(2)
})
})

0 comments on commit 8dfd42d

Please sign in to comment.