Skip to content

Instantly share code, notes, and snippets.

@fronterior
Last active February 25, 2022 22:27
Show Gist options
  • Save fronterior/8b2a2c4f72e62e529e6eb91bc1ba6c11 to your computer and use it in GitHub Desktop.
Save fronterior/8b2a2c4f72e62e529e6eb91bc1ba6c11 to your computer and use it in GitHub Desktop.
const loadImage = (
src: string,
{
save = true,
timeout = Infinity,
crossOrigin,
}: Partial<{
save: boolean;
timeout: number;
crossOrigin: string;
}> = {}
) => {
const img = new Image();
return new TPromise((resolve, reject) => {
if (timeout !== Infinity)
setTimeout(() => {
reject(new Error(`Load timeout for [${src}]:${timeout}ms`));
}, timeout);
img.crossOrigin = crossOrigin;
img.onload = () => {
resolve(save ? img : null);
};
img.onerror = (err) => {
reject(err);
};
img.src = src;
}, timeout).catch((err) => {
if (err instanceof TPromise.TimeoutError) img.removeAttribute("src");
throw err;
});
};
// const img = await loadImage("https://picsum.photos/1000/1000?1", {
// timeout: 1,
// });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment