![](/img/trans.png)
[英]AngularJS TypeError: Cannot call method 'apply' of undefined
[英]setInterval giving me TypeError: Cannot call method 'apply' of undefined
在下面的腳本中,我計划讓我的腳本輪詢設備(家庭自動化)以獲取狀態。 我想每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
值 ,不能將其視為具有setInterval()
期望屬性的函數或對象。
該值是從wrapper()
返回的,當前正在立即調用它。
如果要調用帶參數的函數,可以這樣做:
setInterval(() => this.yourFunciton(yourParemeter), 100)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.