Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ajax/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/logging/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在javascript中实现延迟而不杀死处理器_Javascript_Ajax - Fatal编程技术网

在javascript中实现延迟而不杀死处理器

在javascript中实现延迟而不杀死处理器,javascript,ajax,Javascript,Ajax,我想在某个时间过去后返回函数。在我下面的函数中,返回的东西不起作用(警报被触发) 问题是,在HandlerRequestStateChange中,我初始化了我的数组 function() { xmlHttp.open("POST", "xxx", true); xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xmlHttp.setRequestHeader("Cont

我想在某个时间过去后返回函数。在我下面的函数中,返回的东西不起作用(警报被触发)

问题是,在HandlerRequestStateChange中,我初始化了我的数组

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"); 
}

谢谢

您可以将sleep放置一段时间,然后将return语句放在后面 睡眠


因此,在经过一段时间后,它将从函数返回。

正如您所知,计时器会延迟到线程中的稍后时间,但调用计时器的函数会立即继续执行。如果不锁定浏览器并阻止用户与浏览器交互,就无法延迟当前正在执行的功能

这就是回调的意义所在。不要试图延迟代码的继续执行,而是将函数作为参数提供给“delaying”函数,当它准备好必要的数据时,它将以数据作为参数执行回调函数

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
  });
}

实际上,这里您并没有返回第一个函数中的内容。您是从内部函数返回的,这就是为什么它不是从第一个函数返回的原因。是的,我知道,但如何返回原始函数?是的,但睡眠会杀死处理器(请注意,这是一个异步操作)。所以setTimeout应该是一种方法。