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))
}
@Tusko
Copy link

Tusko commented Oct 30, 2017

can you provide an example how to use it?

@moimikey
Copy link
Author

usage:

waitForLocalStorage('coolProperty', function (value) {
  console.log('coolProperty', value);
});

the 3rd argument isn't necessary.

@Talipemakina
Copy link

Actually you can use something like this.
https://stackoverflow.com/a/42922083

@ivanovcodes
Copy link

not working

@dragGH102
Copy link

The issue with the original gist is the following:

if (!localStorage.getItem(key)) return (timer = setTimeout(waitForLocalStorage.bind(null, key), 100))

Fix:

waitForLocalStorage.bind(null, key, cb )

The callback is undefined after the recursion if we don't pass it over

Thanks @moimikey for the useful snippet - sometimes we "don't know" when a local storage item becomes available, it could be set by a separate component async for example

@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