SetInterval giving me TypeError: cannot call method 'apply' of undefined

In the script below, I plan to have my script poll the device (home automation) for status. I want to do this every 5 seconds. When I run the script without a loop (setInterval), it runs fine. With the loop it works fine the first time. The second time I get an error. I'm running a script with node.js

First script:

//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);

      

Mistake:

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)

      

Can anyone help me with this?

+3


source to share


1 answer


setInterval()

expects its first argument to be function

, which loop

can be defined as:

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

setInterval(loop, 5000);

      



The error is that it loop

currently contains a value undefined

that cannot be treated as a function or an object with properties as setInterval()

expected.

This value is returned from wrapper()

which is currently being called immediately.

+10


source







All Articles