N mol
N mol

Reputation: 571

How to delay execution of a specific function in javascript?

I am working on a network architecture which gives late response to a GET query. I wish to draw the image once I am able to receive from the server. I am trying to increase delay time of display function so that it can be drawn once fetched from server. I am using canvas to display picture from a particular URI. Here is the portion of code which I need to delay running :

var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var img = new Image;
var strDataURI = nameStr;
img.onload = function(){
    context.drawImage(img,0,0, 150,150); // Or at whatever offset you like
};  
img.src = strDataURI;

Please help. Thanks in advance.

Upvotes: 0

Views: 145

Answers (3)

Flame_Phoenix
Flame_Phoenix

Reputation: 17574

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:

  1. You are making the GET request and waiting for the response
  2. 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:

  1. What happens if the image doesn't arrive before you expect? Instead of 1 second, what if it takes 2?
  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?
  3. 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 !

Upvotes: 0

chockleyc
chockleyc

Reputation: 581

There are several options for this. If you insist on making this a timer then you can use setTimeout().

window.setTimeout(function() { // function code here }, 3000);

You could also set your ajax call to be synchronous instead of asynchronous. This will cause other functions to wait until it is complete before running.

$.ajax({
  async: false
});

Finally you could put the draw function in the complete of your ajax call. This function is run after the ajax call is completed.

$.ajax({
  complete: function(result) {
    // code to perform the draw
  }
});

Upvotes: 2

Johannes P
Johannes P

Reputation: 906

Try setTimeout (reference here http://www.w3schools.com/js/js_timing.asp)

Upvotes: 0

Related Questions