diff --git a/.changeset/rich-worms-behave.md b/.changeset/rich-worms-behave.md new file mode 100644 index 000000000..7c9f27b6c --- /dev/null +++ b/.changeset/rich-worms-behave.md @@ -0,0 +1,5 @@ +--- +"@solid-primitives/timer": patch +--- + +Fix createPolled firing twice initially (#632) diff --git a/packages/timer/src/index.ts b/packages/timer/src/index.ts index e7993df10..e016cc74e 100644 --- a/packages/timer/src/index.ts +++ b/packages/timer/src/index.ts @@ -4,8 +4,8 @@ import { createEffect, untrack, Accessor, - createComputed, SignalOptions, + createMemo, } from "solid-js"; import { isServer } from "solid-js/web"; @@ -178,11 +178,9 @@ export function createPolled( if (isServer) { return fn as Accessor; } - 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](); } /** diff --git a/packages/timer/test/index.test.ts b/packages/timer/test/index.test.ts index a6aaaad9e..0333e2587 100644 --- a/packages/timer/test/index.test.ts +++ b/packages/timer/test/index.test.ts @@ -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(); @@ -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) + }) +})