Skip to content

Commit

Permalink
fix(schedule): ensure auto generated task IDs are always unique
Browse files Browse the repository at this point in the history
Previously, we were generating task IDs based on the length of the tasks object. However, this falls
short if any tasks have been unscheduled. For example, let's say we schedule 2 tasks, resulting in
tasks with IDs of `"0"` and `"1"`. Then we unschedule task `"0"`. The length of the tasks object is
now `1`, so when we attempt to schedule the next task we will use the ID `"1"`. This will conflict
with the existing task, causing an error to be thrown.
  • Loading branch information
trezy committed Apr 16, 2022
1 parent 32eccf0 commit 5d674ce
Showing 1 changed file with 15 additions and 1 deletion.
16 changes: 15 additions & 1 deletion lib/schedule.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,13 @@ import { state } from './state.js'



// Variables
let nextTaskID = 0





/**
* Adds a task to the schedule, ensuring it is run on the `requestAnimationFrame` loop.
*
Expand All @@ -23,13 +30,20 @@ export function schedule(task, options = {}) {
context,
framerate = 60,
isPaused = false,
id: taskID = String(Object.keys(state.tasks).length),
} = options
let { id: taskID } = options

if (framerate > 60) {
throw new RangeError(`Framerate may not be higher than 60; requested framerate is ${framerate}.`)
}

if (!taskID) {
taskID = String(nextTaskID)
nextTaskID += 1
} else if ((typeof taskID === 'number') && !Number.isNaN(taskID)) {
nextTaskID = taskID + 1
}

if (state.tasks[taskID]) {
throw new RangeError(`A task with the ID \`${taskID}\` already exists.`)
}
Expand Down

0 comments on commit 5d674ce

Please sign in to comment.