Skip to content

Commit 7788b40

Browse files
authored
fix: allow setting interval repeatedly (#3141)
If we set the interval to the same value multiple times, do not reschedule the task as it is already running on that interval.
1 parent 776cb43 commit 7788b40

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed

packages/utils/src/repeating-task.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@ export interface RepeatingTask {
1111
*
1212
* This only affects the next iteration of the task, if it is currently
1313
* running, that run will not be interrupted.
14+
*
15+
* Setting the interval to the current value has no effect.
1416
*/
1517
setInterval(ms: number): void
1618

@@ -84,6 +86,11 @@ export function repeatingTask (fn: (options?: AbortOptions) => void | Promise<vo
8486

8587
return {
8688
setInterval: (ms): void => {
89+
if (interval === ms) {
90+
// already running at this interval, nothing to do
91+
return
92+
}
93+
8794
interval = ms
8895

8996
// maybe reschedule

packages/utils/test/repeating-task.spec.ts

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,4 +113,29 @@ describe('repeating-task', () => {
113113

114114
expect(count).to.equal(1)
115115
})
116+
117+
it('should not reschedule the task if the interval is updated to the same value', async () => {
118+
let count = 0
119+
120+
const task = repeatingTask(() => {
121+
count++
122+
}, 1_000, {
123+
runImmediately: true
124+
})
125+
task.start()
126+
127+
await delay(100)
128+
129+
task.setInterval(200)
130+
131+
await delay(100)
132+
133+
task.setInterval(200)
134+
135+
await delay(100)
136+
137+
task.stop()
138+
139+
expect(count).to.equal(2)
140+
})
116141
})

0 commit comments

Comments
 (0)