Skip to content

Commit

Permalink
Further get rid of global variables (#11)
Browse files Browse the repository at this point in the history
  • Loading branch information
devlato committed Feb 20, 2021
2 parents 8aa1f79 + a1cc16f commit 38ebf94
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 53 deletions.
2 changes: 1 addition & 1 deletion package.json
@@ -1,6 +1,6 @@
{
"name": "async-wait-until",
"version": "2.0.2",
"version": "2.0.3",
"description": "Waits for a given predicate callback to return a truthy value and resolves",
"main": "dist/index.js",
"types": "dist/index.d.ts",
Expand Down
71 changes: 19 additions & 52 deletions src/index.ts
Expand Up @@ -31,70 +31,37 @@ export class TimeoutError extends Error {
}
}

/**
* Unsupported platform error, which is thrown when the module is used
* neither from a web browser nor from Node.js
* @public
* @class
* @exception
* @category Exceptions
*/
export class UnsupportedPlatformError extends Error {
/**
* Creates an UnsupportedPlatformError instance
* @public
*/
constructor() {
super('Unsupported platform');

Object.setPrototypeOf(this, UnsupportedPlatformError.prototype);
}
}

/**
* A utility function for cross-platform type-safe scheduling
* @private
* @returns Returns a proper scheduler instance depending on the current environment
* @throws [[UnsupportedPlatformError]] If the current environment is not supported, e.g. it's neither a web browser nor Node.js
* @throws Error
* @category Utilities
*/
const getScheduler = (): Scheduler => {
if (
// Not a web browser
window == null ||
// Not Node.js
module == null ||
global == null
) {
throw new UnsupportedPlatformError();
}
const getScheduler = (): Scheduler => ({
schedule: (fn, interval) => {
let scheduledTimer: number | NodeJS.Timeout | undefined = undefined;

return {
schedule: (fn, interval) => {
let scheduledTimer: number | NodeJS.Timeout | undefined = undefined;

const cleanUp = (timer: number | NodeJS.Timeout | undefined) => {
if (timer != null) {
(window != null ? window : global).clearTimeout(timer as number);
}
const cleanUp = (timer: number | NodeJS.Timeout | undefined) => {
if (timer != null) {
clearTimeout(timer as number);
}

scheduledTimer = undefined;
};
scheduledTimer = undefined;
};

const iteration = () => {
cleanUp(scheduledTimer);
fn();
};
const iteration = () => {
cleanUp(scheduledTimer);
fn();
};

scheduledTimer = (window != null ? window : global).setTimeout(iteration, interval);
scheduledTimer = setTimeout(iteration, interval);

return {
cancel: () => cleanUp(scheduledTimer),
};
},
};
};
return {
cancel: () => cleanUp(scheduledTimer),
};
},
});

/**
* Delays the execution by the given interval, in milliseconds
Expand Down

0 comments on commit 38ebf94

Please sign in to comment.