-
-
Notifications
You must be signed in to change notification settings - Fork 287
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Simplify delay behaviour, add JSDoc comments
- Loading branch information
Showing
1 changed file
with
25 additions
and
15 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,32 +1,42 @@ | ||
// adapted from https://github.com/sindresorhus/multi-download/blob/v4.0.0/index.js | ||
// Adapted from https://github.com/sindresorhus/multi-download/blob/v4.0.0/index.js | ||
// to take File as input https://developer.mozilla.org/en-US/docs/Web/API/File | ||
const delay = milliseconds => new Promise(resolve => { | ||
setTimeout(resolve, milliseconds); | ||
}); | ||
|
||
const download = async (file) => { | ||
/** | ||
* Creates a promise that resolves after the specified number of milliseconds | ||
*/ | ||
const delay = (milliseconds: number): Promise<void> => { | ||
return new Promise((resolve) => setTimeout(resolve, milliseconds)); | ||
}; | ||
|
||
/** | ||
* Downloads a single file | ||
* @param file - An instance of the File type representing the file to download | ||
*/ | ||
const download = async (file: File): Promise<void> => { | ||
const a = document.createElement('a'); | ||
const url = URL.createObjectURL(file); | ||
a.download = file.name; | ||
a.href = url; | ||
a.style.display = 'none'; | ||
document.body.append(a); | ||
document.body.appendChild(a); | ||
a.click(); | ||
|
||
// Chrome requires the timeout | ||
await delay(100); | ||
await delay(100); // Needed for Chrome | ||
a.remove(); | ||
|
||
URL.revokeObjectURL(url); | ||
}; | ||
|
||
const multiDownload = async (files) => { | ||
/** | ||
* Initiates multiple file downloads with a delay between each one | ||
* @param files - An array of instances of the File type representing the files to download | ||
*/ | ||
const multiDownload = async (files: readonly File[]): Promise<void> => { | ||
if (!files) { | ||
throw new Error('`files` required'); | ||
} | ||
|
||
for (const [index, file] of files.entries()) { | ||
await delay(index * 1000); // eslint-disable-line no-await-in-loop | ||
|
||
// Trigger a download every second | ||
for (const file of files) { | ||
await delay(1000); | ||
download(file); | ||
} | ||
} | ||
}; |