Skip to content

Instantly share code, notes, and snippets.

@moimikey
Last active October 26, 2023 15:31
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save moimikey/07501755bcba3aa409b0 to your computer and use it in GitHub Desktop.
Save moimikey/07501755bcba3aa409b0 to your computer and use it in GitHub Desktop.
/**
* Michael Scott Hertzberg <mshertzberg@gmail.com> (http://hertzber.gs)
*
* recursively check for set localStorage value every 100ms.
* this will also safely clear the timeout once found.
* can be used callback style or directly.
* functionally pure.
*/
function waitForLocalStorage(key, cb, timer) {
if (!localStorage.getItem(key)) return (timer = setTimeout(waitForLocalStorage.bind(null, key, cb), 100))
clearTimeout(timer)
if (typeof cb !== 'function') return localStorage.getItem(key)
return cb(localStorage.getItem(key))
}
@jamesryan-dev
Copy link

jamesryan-dev commented Feb 16, 2022

correct gist following @dragGH102 's fix:

function waitForLocalStorage(key, cb, timer) {
	if ( ! localStorage.getItem( key ) ) {
		return timer = setTimeout(
			waitForLocalStorage.bind( null, key, cb ),
			100
		)
	}
	clearTimeout( timer )
	if ( typeof cb !== 'function' ) {
		return localStorage.getItem( key )
	}
	return cb( localStorage.getItem( key ) )
}

@moimikey
Copy link
Author

moimikey commented Oct 26, 2023

@dragGH102 thanks! good catch! gist has been updated.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment