Skip to content

Instantly share code, notes, and snippets.

@mimshins
Created August 5, 2025 12:57
Show Gist options
  • Save mimshins/f9c402e57876bbe7cbaf04f5ecd71436 to your computer and use it in GitHub Desktop.
Save mimshins/f9c402e57876bbe7cbaf04f5ecd71436 to your computer and use it in GitHub Desktop.
This function repeatedly checks local storage for a key-value pair until it either finds a match, or a specified timeout is reached.
/**
* Waits for a specific value to be present in local storage.
*
* @param key The key to look for in local storage.
* @param [options] The options to configure the waiting behavior.
* @returns A promise that resolves when the condition is met, or rejects if the timeout is reached.
*/
export const waitForStorage = (
key: string,
options?: {
/**
* The expected value for the key. If not provided,
* the function will resolve as soon as the key exists with any value.
*/
value?: string;
/**
* The maximum time (in milliseconds) to wait before rejecting the promise.
*
* @default 2000
*/
timeout?: number;
/**
* The interval (in milliseconds) at which to check for the value.
*
* @default 100
*/
checkInterval?: number;
},
): Promise<void> => {
const { timeout = 2000, checkInterval = 100, value } = options ?? {};
const maxCheck = timeout / checkInterval;
let checkCount = 0;
return new Promise<void>((resolve, reject) => {
const check = () => {
checkCount++;
const itemValue = localStorage.getItem(key);
// Check if the item exists and, if a value was provided, if it matches
if (itemValue !== null && (value === undefined || itemValue === value)) {
resolve();
} else if (checkCount > maxCheck) {
reject(
new Error(
`Timeout of ${timeout}ms exceeded while waiting for key "${key}"`,
),
);
} else {
// Condition not met and timeout not reached, schedule the next check
window.setTimeout(check, checkInterval);
}
};
check();
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment