Your sleep function is blocked, what you really want is a recursive function that returns a promise after checking url n times with a delay of y seconds, etc.
Something like that
function chk(target, times, delay) { return new Promise((res, rej) => { // return a promise (function rec(i) { // recursive IIFE fetch(target, {mode: 'no-cors'}).then((r) => { // fetch the resourse res(r); // resolve promise if success }).catch( err => { if (times === 0) // if number of tries reached return rej(err); // don't try again setTimeout(() => rec(--times), delay ) // otherwise, wait and try }); // again until no more tries })(times); }); }
Used as
var t = "https://i.stack.imgur.com/Ya15i.jpg"; chk(t, 3, 1000).then( image => { console.log('success') }).catch( err => { console.log('error') });
And note that this is not interrupted by 404 or 500, any response is a successful request.
source share