gpt4 book ai didi

javascript - setInterval 给我 TypeError : Cannot call method 'apply' of undefined

转载 作者:搜寻专家 更新时间:2023-10-31 23:30:07 26 4
gpt4 key购买 nike

在下面的脚本中,我计划让我的脚本轮询设备(家庭自动化)的状态。我想每 5 秒执行一次。当我在没有循环(setInterval)的情况下运行脚本时运行正常。通过循环,它第一次运行良好。第二次我得到一个错误。我用 node.js 运行脚本

首先是脚本:

//import node module request
var request = require('request');

//function to get status of a device
function wrapper (url, device, filter, service) {
request(url, function (error, response, body) {
if (!error && response.statusCode == 200) {
obj = JSON.parse(body);
for (var i = 0; i < obj[device].states.length; i++) {
if (obj[device].states[i].service === service && obj[device].states[i].variable === filter) {
deviceStatus = obj[device].states[i].value;
console.log("deviceStatus inside function: " + deviceStatus);
//call the compareTime function
compareTime(deviceStatus);
}
}
}
return 3;
});
};

function compareTime() {
var hour = new Date().getHours();
console.log(hour);
if ( 8 <= hour && hour <= 21 ) {
//var deviceStatus = 0;
console.log("deviceStatus :" + deviceStatus);
if (deviceStatus === '1') {
request('url', function (error, response, body) {
if (!error && response.statusCode == 200) {
}
})
request('url', function (error, response, body) {
if (!error && response.statusCode == 200) {
}
})
} else {
console.log("deviceStatus :" + deviceStatus);
}
} else {
console.log("deviceStatus :" + deviceStatus);
}
};


loop = wrapper('url', 'Device_Num_21', 'Status', 'urn:upnp-org:serviceId:SwitchPower1');

//call the function wrapper with arguments
setInterval(loop, 5000);

错误:

node stack.js
deviceStatus inside function: 1
21
deviceStatus :1

timers.js:261
callback.apply(this, args);
^
TypeError: Cannot call method 'apply' of undefined
at wrapper [as _onTimeout] (timers.js:261:14)
at Timer.listOnTimeout [as ontimeout] (timers.js:112:15)

谁能帮我解决这个问题?

最佳答案

setInterval()期望它的第一个参数是一个 function,它的 loop 可以定义为:

function loop() {
wrapper('url', 'Device_Num_21', 'Status', 'urn:upnp-org:serviceId:SwitchPower1');
}

setInterval(loop, 5000);

错误是因为 loop 当前持有 undefined value ,它不能被视为具有 setInterval() 期望的属性的函数或对象。

该值正在从 wrapper() 返回,当前正在立即调用它。

关于javascript - setInterval 给我 TypeError : Cannot call method 'apply' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26329276/

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