R
R
rundll322022-02-01 19:38:42
JavaScript
rundll32, 2022-02-01 19:38:42

Is the delay before uploading files not working properly?

There is a loop that iterates over image links and sends them to the Download method (taken from StackOverflow), which causes the browser to download them.

function Download(url, name) {
        fetch(url)
            .then(resp => resp.blob())
            .then(blob => {
                const url = window.URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.style.display = 'none';
                a.href = url;
                // the filename you want
                a.download = name;
                document.body.appendChild(a);
                a.click();
                window.URL.revokeObjectURL(url);
            })
            .catch(() => alert("Ошибка загрузки файла"));

Before calling the method, I tried different ways to create a wait, all sorts of while that wait until the desired number of milliseconds have passed, but the delay always only works for the first element. This causes the files to be downloaded in a different order, even though all the logs say that the array is sorted correctly. Similarly, if after the call, as if the loop still works without delay. Then I found this wrapper solution for the call:
function DownloadWorker(url, name) {
        setTimeout(function() {
            Download(url, name);
        }, DELAY);
    }

Where DELAY is a constant. But the result is the same, the delay is only at the beginning, and the files are mixed up.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
G
GrayHorse, 2022-02-01
@rundll32

Once:

function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

Two:
function download(blob, name, url) {
    const anchor = document.createElement("a");
    anchor.setAttribute("download", name || "");
    const blobUrl = URL.createObjectURL(blob);
    anchor.href = blobUrl + (url ? ("#" + url) : "");
    anchor.click();
    setTimeout(() => URL.revokeObjectURL(blobUrl), 5000);
}

I recommend adding the original link url(third parameter) to blobUrl, it may come in handy later - see where (from which link) the file was downloaded.
For example:
blob:https://imgur.com/11fb6df9-e45b-4acf-b3eb-60d5d4656747#https://i.imgur.com/X92aA5Y.jpeg

Together:
for (const url of urls) {
    const resp = await fetch(url);
    const blob = await resp.blob();
    const name = new URL(url).pathname.match(/[^\/]*$/)[0];
    download(blob, name, url);
    await sleep(200);
}

N
Nadim Zakirov, 2022-02-02
@zkrvndm

Your method is crooked. Use async / await if you want to download files sequentially:

Expand Example
async function downloadFiles(links) {
  
  for (var n = 0; n < links.length; n++) {
    
    try {
      
      var blob = await (await fetch(links[n])).blob();
      var blob_url = URL.createObjectURL(blob);
      var blob_name = new URL(links[n]).pathname.split('/').pop();
      
      var a = document.createElement('a');
      a.style.display = 'none';
      a.href = blob_url;
      
      a.setAttribute('download', blob_name);
      
      document.body.appendChild(a);
      a.click();
      
      console.log('Файл '+links[n]+' скачан');
      
      // Делаем задержку на 2 секунды:
      
      await new Promise(function(s) {
        setTimeout(s, 2000);
      });
      
      URL.revokeObjectURL(blob_url);
      
    }
    
    catch(err) {
      
      console.log('Ошибка, не удалось скачать файл ' + links[n]);
      console.erroe(err);
      
      // Делаем задержку на 2 секунды:
      
      await new Promise(function(s) {
        setTimeout(s, 2000);
      });
      
    }
    
  }
  
  console.log('Загрузка файлов завершена!');
  
}

To download files from links, simply call the downloadFiles function passing an array of links into it:
downloadFiles([
    'https://i.imgur.com/X92aA5Y.jpeg', 
    'https://i.imgur.com/X92aA5Y.jpeg',
    'https://i.imgur.com/X92aA5Y.jpeg'
]);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question