Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
4 changed files
with
110 additions
and
20 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,2 +1,3 @@ | ||
export * from "./colors" | ||
export * from "./control" | ||
export * from "./schedule" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,48 @@ | ||
import { AsyncVoid } from "@devicescript/core" | ||
|
||
/** | ||
* Schedules a handler to be called at a later time. Executes timeout before interval if combined. | ||
* | ||
* @param handler function to execute | ||
* @param options options to configure the scheduling | ||
* @returns clear timer function | ||
*/ | ||
export function schedule( | ||
handler: () => AsyncVoid, | ||
options: { | ||
/** | ||
* Time in milliseconds to wait before the first execution of the handler. | ||
*/ | ||
timeout?: number | ||
/** | ||
* Time in milliseconds to wait before executing the handler in an internval. | ||
*/ | ||
interval?: number | ||
} | ||
) { | ||
let timerId: number | ||
let intervalId: number | ||
const unsub = () => { | ||
if (timerId) clearTimeout(timerId) | ||
if (intervalId) clearInterval(intervalId) | ||
timerId = intervalId = undefined | ||
} | ||
|
||
if (!handler) return unsub | ||
|
||
let { interval, timeout } = options | ||
if (interval === undefined && timeout === undefined) timeout = 20 | ||
if (timeout >= 0 && interval >= 0) { | ||
timerId = setTimeout(async () => { | ||
await handler() | ||
// check if cancelled or schedule | ||
if (timerId !== undefined) | ||
intervalId = setInterval(handler, interval) | ||
}, 20) | ||
} else if (timeout) { | ||
timerId = setTimeout(handler, timeout) | ||
} else if (interval) { | ||
intervalId = setInterval(handler, interval) | ||
} | ||
return unsub | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters