gpt4 book ai didi

javascript - 如何让递归调用的 setTimeout 函数在后台保持事件状态

转载 作者:行者123 更新时间:2023-11-30 15:53:33 27 4
gpt4 key购买 nike

我有一个使用 setTimeout 递归调用函数的网页。该页面还有一个 html5 短信链接(js 重定向不是 href)。当 msg 应用程序启动时,网页似乎并没有像我希望的那样继续在后台运行这些功能。我使用一个全局计数器变量来计算并在页面上显示 checkAuth 后台函数运行了多少次,当我返回页面时,这个数字并没有像我第一次进入页面时那样每 3 秒递增一次,也没有它是否像我希望的那样每 3 秒再次开始递增。在 msg 应用程序将浏览器发送到后台之前,这两个功能似乎都在运行。

即使它们不在后台运行我也同意,但是我如何让它在前台重新启动?这是我需要做的最低限度。谢谢。

//event that starts the process
$("#connect").click(function (){checkAuth();});

function checkAuth() {

//global var that counts how many times this function is called
authAttempts++;

//displays checkAuth run count on page.
$("#aa").text(authAttempts.toString());

$.get(encodeURI("myurl.aspx?phone=" + getCookie("phone") + "&ec=" + getCookie("ec") + "&authToken=" + getCookie("at") + "&uh=" + getCookie("uh") + "&mode=" + getCookie("mode")), function (data) {
$("#ajaxResults").html(data);
if ($("#authYes").length) {
var mode = getCookie("mode");
if (mode == "drv") {
window.location.replace("drv.aspx" + query);
}
else if (mode == "dsp") {
window.location.replace("dsp.aspx" + query);
}
}

else if ($("#authPending").length) {

if (++attempts >= 10) {
alert("Authentication Timed-out. Please try to connect again");
$("#link").html("");

// if this times out then force a new authentication value
// to keep the pending value from being stuck

var r = Math.random() * 1000000000;
var ri = r.toFixed(0);
var aToken = ri.toString();

$("#at").val(aToken);
setCookie("authToken", aToken, 1);
}
else {
setTimeout(checkAuth, 3000);
}
}

//must have been no good so start the authentication process
//authSent is global var to record if auth has already been sent
else if (authSent == false) {
authSent = true;
sendAuth();
}
});
}

function sendAuth() {
// generate a new token

var r = Math.random() * 1000000000;
var ri = r.toFixed(0);
var aToken = ri.toString();

$("#at").val(aToken);

setCookie("at", $("#at").val(), 1);

checkAuth();
//launch msgs app so they can send a prefilled text message
setTimeout(showMsgsApp, 500);
}
function showMsgsApp() {
window.location = "sms:19789652017&body=" + $("#at").val() + "-" + $("#ec").val() + "-" + $("#mode").val() + "-" + $("#uh").val();
}

最佳答案

你可以使用网络 worker ,即使你的页面在后台也能执行你的代码,我没有在手机上用你的案例测试过它,但它确实有效,用于执行代码,而 chrome 选项卡是开放但不活跃,因此它可能适合您的需要。

想法是使用一个 webworker 递归地运行超时,并在每次滴答时向窗口发送一条消息,窗口将监听给定的消息,并在每次收到消息时执行 checkAuth。

例子:

创建一个简单的网络 worker :worker.js

setInterval(function(){
postMessage('triggerAuth');
}, 3000)

现在在您的页面上,您应该执行 webworker,而不是创建第一个超时:

var authWorker = new Worker("worker.js");

authWorker.onmessage = function (oEvent) {
checkAuth();
};

然后确保在成功完成操作后,终止 worker。

authWorker.terminate();

原因是,当选项卡未激活时,它不会响应超时或间隔,这就是您的代码未被执行的原因。

同样,这是在不活动的浏览器选项卡上测试的,不确定它是否与您的移动示例相同。

关于javascript - 如何让递归调用的 setTimeout 函数在后台保持事件状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38933766/

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