diff --git a/defaultmodules/weather/node_helper.js b/defaultmodules/weather/node_helper.js index a83a7caf3d..4a4cbe1b84 100644 --- a/defaultmodules/weather/node_helper.js +++ b/defaultmodules/weather/node_helper.js @@ -88,7 +88,7 @@ module.exports = NodeHelper.create({ }); // Start periodic fetching - provider.start(); + provider.start(config.initialLoadDelay); Log.log(`Weather provider ${identifier} initialized for instance ${instanceId}`); } catch (error) { diff --git a/defaultmodules/weather/weatherprovider.js b/defaultmodules/weather/weatherprovider.js index 8e4a541917..0ba05acff6 100644 --- a/defaultmodules/weather/weatherprovider.js +++ b/defaultmodules/weather/weatherprovider.js @@ -28,9 +28,12 @@ class WeatherProvider { this.onErrorCallback = onError; } - /** Start periodic fetching. */ - start () { - this.fetcher?.startPeriodicFetch(); + /** + * Start periodic fetching. + * @param {number} [initialDelay] - Delay before the first fetch in ms + */ + start (initialDelay = 0) { + this.fetcher?.startPeriodicFetch(initialDelay); } /** Stop periodic fetching. */ diff --git a/js/http_fetcher.js b/js/http_fetcher.js index eca4896080..747725c53c 100644 --- a/js/http_fetcher.js +++ b/js/http_fetcher.js @@ -127,9 +127,16 @@ class HTTPFetcher extends EventEmitter { /** * Starts periodic fetching + * @param {number} [initialDelay] - Delay before the first fetch in ms */ - startPeriodicFetch () { - this.fetch(); + startPeriodicFetch (initialDelay = 0) { + this.clearTimer(); + + if (initialDelay > 0) { + this.reloadTimer = setTimeout(() => this.fetch(), initialDelay); + } else { + this.fetch(); + } } /** diff --git a/tests/unit/functions/http_fetcher_spec.js b/tests/unit/functions/http_fetcher_spec.js index 5162fb760a..b6e3900ad4 100644 --- a/tests/unit/functions/http_fetcher_spec.js +++ b/tests/unit/functions/http_fetcher_spec.js @@ -51,6 +51,25 @@ describe("HTTPFetcher", () => { expect(text).toBe(responseData); }); + it("should delay the first fetch when an initial delay is configured", async () => { + vi.useFakeTimers(); + const fetchSpy = vi.spyOn(globalThis, "fetch").mockResolvedValue( + new Response("test data") + ); + fetcher = new HTTPFetcher(TEST_URL, { reloadInterval: 60000 }); + + fetcher.startPeriodicFetch(15000); + + expect(fetchSpy).not.toHaveBeenCalled(); + await vi.advanceTimersByTimeAsync(14999); + expect(fetchSpy).not.toHaveBeenCalled(); + await vi.advanceTimersByTimeAsync(1); + expect(fetchSpy).toHaveBeenCalledTimes(1); + + fetchSpy.mockRestore(); + vi.useRealTimers(); + }); + it("should emit error event on network failure", async () => { server.use( http.get(TEST_URL, () => {