gpt4 book ai didi

javascript - 在不杀死处理器的情况下在 javascript 中实现延迟

转载 作者:行者123 更新时间:2023-11-29 22:41:31 25 4
gpt4 key购买 nike

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

事情是在我的 handleRequestStateChange 中我初始化了 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");
}

谢谢!

最佳答案

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

这就是回调点发挥作用的地方。您不是试图延迟代码的继续执行,而是提供一个函数作为“延迟”函数的参数,当它准备好必要的数据时,它会以数据作为参数执行回调函数。

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

关于javascript - 在不杀死处理器的情况下在 javascript 中实现延迟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2416223/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com