views:

116

answers:

2

Hi.

I want to return the function when a certain time has passed. In my function below the return thing didn't work(the alert was triggered).

The thing is that in my handleRequestStateChange I initialize myArray.

function() {    
  xmlHttp.open("POST", "xxx", true);
  xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  xmlHttp.setRequestHeader("Content-Length", 10);
  xmlHttp.onreadystatechange = handleRequestStateChange;
  xmlHttp.send(locParam);

  setTimeout(function() { return myArray; }, 5000);
  alert("end sleep"); 
}

Thanks!

A: 

You can put the sleep for certain time, then put the return statement after the sleep.

So that it will return from the function after some time is passed.

pavun_cool
Yes, but sleep kills the processor(mind that this is an asynchronous action). So setTimeout should be the way to go.
Silviu Postavaru
+1  A: 

As you're aware, timers are delayed until later in the thread, but the function that calls them continues to execute straight away. There's no way to delay the currently executing function without locking up the browser and preventing user interaction with the browser.

This is where the point of callbacks come into play. Instead of trying to delay continued execution of code, you supply a function as a parameter to the "delaying" function, and when it has it's necessary data ready, it executes the callback function with the data as a parameter.

function submitRequest(callback) {     
  xmlHttp.open("POST", "xxx", true); 
  xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); 
  xmlHttp.setRequestHeader("Content-Length", 10); 
  xmlHttp.onreadystatechange = function ()
  {
    if (xmlHttp.readyState == 4 && xml.status == 200)
    {
      var myArray;
      // do something with data
      callback(myArray);  // execute the callback function
    }
  }; 
  xmlHttp.send(locParam); 
} 

function someCallingFunction()
{
  // call submitRequest with an anonymous function as the callback parameter
  submitRequest(function (myArray)  
  {
    alert("end sleep");  
    // do something with myArray
  });
}
Andy E