每x秒调用一个函数的JavaScript例程
我有一个JavaScript,我想每5秒运行一次。它在我的树莓Pi上显示我的GPIO引脚的状态。但是现在,如果pin改变了我正在运行的另一个脚本的状态,它不会更新。我试图输入每x秒调用一个函数的JavaScript例程,javascript,Javascript,我有一个JavaScript,我想每5秒运行一次。它在我的树莓Pi上显示我的GPIO引脚的状态。但是现在,如果pin改变了我正在运行的另一个脚本的状态,它不会更新。我试图输入var myVar=setInterval(function(){change\u pin()},1000)但这对我没有帮助 代码看起来像这样 //TheFreeElectron 2015, http://www.instructables.com/member/TheFreeElectron/ //JavaScript,
var myVar=setInterval(function(){change\u pin()},1000)代码>但这对我没有帮助
代码看起来像这样
//TheFreeElectron 2015, http://www.instructables.com/member/TheFreeElectron/
//JavaScript, uses pictures as buttons, sends and receives values to/from the Rpi
//These are all the buttons
var button_0 = document.getElementById("button_0");
var button_1 = document.getElementById("button_1");
var button_2 = document.getElementById("button_2");
var button_3 = document.getElementById("button_3");
var button_4 = document.getElementById("button_4");
var button_5 = document.getElementById("button_5");
var button_6 = document.getElementById("button_6");
var button_7 = document.getElementById("button_7");
//Create an array for easy access later
var Buttons = [ button_0, button_1, button_2, button_3, button_4, button_5, button_6, button_7];
//This function is asking for gpio.php, receiving datas and updating the index.php pictures
function change_pin ( pic ) {
var data = 0;
//send the pic number to gpio.php for changes
//this is the http request
var request = new XMLHttpRequest();
request.open( "GET" , "gpio.php?pic=" + pic, true);
request.send(null);
//receiving informations
request.onreadystatechange = function () {
if (request.readyState == 4 && request.status == 200) {
data = request.responseText;
//update the index pic
if ( !(data.localeCompare("0")) ){
Buttons[pic].src = "data/img/red/red_"+pic+".jpg";
}
else if ( !(data.localeCompare("1")) ) {
Buttons[pic].src = "data/img/green/green_"+pic+".jpg";
}
else if ( !(data.localeCompare("fail"))) {
alert ("Something went wrong!" );
return ("fail");
}
else {
alert ("Something went wrong!" );
return ("fail");
}
}
//test if fail
else if (request.readyState == 4 && request.status == 500) {
alert ("server error");
return ("fail");
}
//else
else if (request.readyState == 4 && request.status != 200 && request.status != 500 ) {
alert ("Something went wrong!");
return ("fail"); }
}
return 0;
}
change_pin pic参数是否可选?如果您必须在setInterval内为每个按钮执行change_pin。如果您手动更新页面(如按键盘上的F5),它会更改值吗?从gpio.php
返回的数据是否正确?另外,尝试使用setInterval
而不将其分配给变量。在setInterval(function(){change\u pin()…)
中,您似乎没有为pic传递值。如果我手动更新页面,该值将更改为正确的值。我的问题是,该函数只运行一个值(当加载页面时)。