Implement delay in javascript without killing the processor
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 = handleReq开发者_Python百科uestStateChange;
xmlHttp.send(locParam);
setTimeout(function() { return myArray; }, 5000);
alert("end sleep");
}
Thanks!
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
});
}
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.
精彩评论