Skip to content

Commit

Permalink
add maxWaitMs argument
Browse files Browse the repository at this point in the history
  • Loading branch information
Juliette Pretot committed Nov 21, 2019
1 parent 4410666 commit b395a59
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 6 deletions.
33 changes: 28 additions & 5 deletions AxeObserver.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,34 @@ const requestIdleCallback =
}

// Define own debounce function to avoid excess dependencies
// Ref: https://chrisboakes.com/how-a-javascript-debounce-function-works/
function debounce(callback, wait) {
function debounce(callback, debounceMs, maxWaitMs) {
let timeout
let queuedSince
return (...args) => {
clearTimeout(timeout)
timeout = setTimeout(() => callback.apply(this, args), wait)

const isExecutionAlreadyQueued = !!queuedSince

if (!isExecutionAlreadyQueued) {
queuedSince = Date.now()
}

const execute = () => {
queuedSince = null
return callback.apply(this, args)
}

const queueExecution = () => {
timeout = setTimeout(execute, debounceMs)
}

const isMaxDelayExceeded = Date.now() - queuedSince > maxWaitMs

if (isMaxDelayExceeded) {
execute()
} else {
queueExecution()
}
}
}

Expand Down Expand Up @@ -53,14 +75,15 @@ export default class AxeObserver {

axeCore.configure(axeConfiguration)
}
observe(targetNode, debounceMs = 1000) {
observe(targetNode, debounceMs = 1000, maxWaitMs = debounceMs * 10) {
if (!targetNode) {
throw new Error('AxeObserver.observe requires a targetNode')
}

const scheduleAudit = debounce(
() => requestIdleCallback(() => this._auditTargetNode(targetNode)),
debounceMs
debounceMs,
maxWaitMs
)
const mutationObserver = new window.MutationObserver(scheduleAudit)

Expand Down
3 changes: 2 additions & 1 deletion README.MD
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,8 @@ The `AxeObserver` constructor takes two parameters:
The `AxeObserver.observe` method takes two parameters:

- `targetNode` (required). The node that should be observed & analyzed.
- `debounceMs` (optional, defaults to `1000`). The number of milliseconds to wait for component updates to cease before performing an analysis of all the changes.
- `debounceMs` (optional, defaults to `1000`). The number of milliseconds that updates should cease before an analysis is performed.
- `maxWaitMs` (optional, defaults to `debounceMs * 10`). Number of milliseconds after which an analysis will be performed, even if the targetNode is still updating.

## Credits

Expand Down

0 comments on commit b395a59

Please sign in to comment.