I'm new to JavaScript from Java, and I'm trying to implement a sleep(millis)
function. Basically I need to make a request to an endpoint, and if it returns an error, wait a while and make the request again...
I've found JavaScript's setTimeout()
function, but it has a strange (for me) behaviour, because it seems that the code is still running, and I don't want to do anything but wait...
After a little research I've found this function here:
function sleep(milliseconds) {
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > milliseconds){
break;
}
}
}
With this function I achieve exactly what I want, but I understand it may not be the proper way to do it and I didn't find any other solutions like this... So, I'd like to know, in your opinion, is this:
- A perfectly valid solution?
- A not too bad workaround?
- Just painful to your eyes?