Suggestion
My suggestion is to NOT delay it at all. As chockleyc said, waiting for the response would be the best option.
Cases
There are the following possible scenarios:
- You are making the GET request and waiting for the response
- You are not making the request manually, and it is simply loaded with page
You make the GET request manually
If you are making the GET query yourself, my strong recommendation is to use Promise
like this:
var getRequest = new Promise(function(resolve, reject){
//We call resolve(...) when what we were doing async succeeded, and reject(...) when it failed.
//In this example, we use setTimeout(...) to simulate async code.
var oReq = new XMLHttpRequest();
oReq.onload = function(e) {
resolve(oReq.response);
}
oReq.open("GET", "www.bananas.com");
oReq.send();
});
and then you would use it like:
var getRequest()
.then(console.log);
Which in this case would print the response. If you are not familiar I recommend the MDN Promises documentation.
Another alternative is to simply use the XMLHttp from JavaScript without promises. You can read more examples in the MDN documentation as well or if it is too confusing for you give a try to the kirupa tutorial.
You don't make the GET request manually
In this case, I recommend you listen to the GET request, and then perform a specific action once its response arrives. A good solution for this can be found in this response:
Where you will find a mini library that will listen to ALL GET requests. This way, every time you receive a GET request you can filter it by what you want and execute your code.
If the previous code is too complex for you, you can also have a look at this much simpler alternative:
You really insist in using a timer
The worst solution by far. Why? try answering these questions:
- What happens if the image doesn't arrive before you expect? Instead of 1 second, what if it takes 2?
- How do you know for sure exactly how long the GET request will take? Will you make a median of 100 requests? What if you get that one request that is outside the median?
- Assuming you always wait the longest possible time (to ensure everything works) why should the majority of your users have a weaker experience?
But if you insist on it, then both answers from "chockleyc" and from "Johannes P" should clarify all your questions.
That's all for now, I hope it helps !