gpt4 book ai didi

javascript - setInterval 每 n 秒调用一个函数

转载 作者:行者123 更新时间:2023-12-02 17:32:36 24 4
gpt4 key购买 nike

我遇到了每 1 秒调用一个函数的障碍。该代码在页面加载时运行一次,如果我手动刷新页面,它会再次运行。提前致谢!

这是代码:

//query the function S1M1StatusInt every second

setInterval(function () {S1M1StatusInt()}, 1000);

下面的 Test_tag 是一个范围为 0-4 的 int :="Skid 1"。Test_tag:是寻址 PLC 变量的语法。

// Change the Skid 1 Meter 1 block from grey to red or green based on "Skid 1".Test_tag

function S1M1StatusInt() {
var dim1= :="Skid 1".Test_tag:;

switch (dim1)
{
case 1:
document.getElementById("S1M1Status").className ="";
document.getElementById("S1M1Status").className = "RedBlock";
break;
case 2:
document.getElementById("S1M1Status").className ="";
document.getElementById("S1M1Status").className = "RedBlock";
break;
case 3:
document.getElementById("S1M1Status").className ="";
document.getElementById("S1M1Status").className = "GreenBlock";
break;
}}

-----编辑 epascarello-----

function CheckS1M1StatusInt(){
$.ajax({
Type: "Get",
url: "Meter_Status/S1M1_Status.htm",
data: {*** what goes in here if I am retreving data***},
success: successCheck,
error: errorcheck
});
}

function successCheck(data){
switch (data)
{
case 1:
document.getElementById("S1M1Status").className ="";
document.getElementById("S1M1Status").className = "RedBlock";
break;
case 2:
document.getElementById("S1M1Status").className ="";
document.getElementById("S1M1Status").className = "RedBlock";
break;
case 3:
document.getElementById("S1M1Status").className ="";
document.getElementById("S1M1Status").className = "GreenBlock";
break;
};
Console.log(data);
window.setTimeout(checkServer,1000);
}

function errorCheck(){
console.log(arguments);
}

最佳答案

问题是浏览器不会不断更新服务器端代码。 PLC 标签[无论是什么]被渲染一次,它不会不断从服务器获取新值。这就是为什么它永远不会改变。

您需要做的是向服务器发出 Ajax 调用并检查状态。

function checkServer() {
$.ajax({
type: "POST",
url: "URLToPageToCheck/foo.php",
data: { "itemX" : "whatYouWantToSendUp"},
success: successCheck,
error: errorCheck
});
}

function successCheck(data){
//Logic Check Here
console.log(data);
//Call checkServer again with a delay
window.setTimeout(checkServer,1000);
}
function errorCheck(){
console.log(arguments);
}

关于javascript - setInterval 每 n 秒调用一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22921712/

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