javascript – setInterval给我TypeError:无法调用undefined的方法’apply’

在下面的脚本中,我计划让我的脚本轮询设备(家庭自动化)以获取状态.我想每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() {
    wrapper('url', 'Device_Num_21', 'Status', 'urn:upnp-org:serviceId:SwitchPower1');
}

setInterval(loop, 5000);

错误是因为循环当前持有undefined value,不能将其视为具有setInterval()期望属性的函数或对象.

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

上一篇:javascript – Setinterval与指数时间减少


下一篇:Javascript函数setInterval()只能运行一次