简体   繁体   中英

Functions inside setInterval in JavaScript

I have a problem to call functions inside the setInterval function in JavaScript. My code:

setInterval(function() {
y.on('deviceconnected', function(device) {
    console.log("Power off the device");

    var state = false;
    y.setPower(device, state, 300);
});
}, 3000);

That function powers off my room bulb and it works fine out of the setInterval. Unfortunately, inside the setInterval it doesn't work at all. Program never enters the function and for example print: Power off the device.

How should I call that functions inside the setInterval?

You are doing it backwards compared to what is needed. Yes, docs write

Before attempting to control any devices you must have completed device discovery and connection.

but it means that it has to happen before controlling, once. Not once every 3 seconds.
You would need the complete opposite:

...
y.on('deviceconnected', function(device) {
  y.setPower(device,true,300);
  setInterval(function(){
    y.setBrightness(device,50,300);
    setTimout(function(){
      y.setBrightness(device,100,300);
    },1500);
  },3000);
});

Totally ad-hoc example, copied the pieces from docs. 300-s are transition times (in ms), first it powers up the device, then it tries to toggle between 50% and 100% brightness at every 1.5 seconds (more-or-less, that inner timeout is not very nice, it could rather use a state variable instead).

Sorry that I didnt mantioned but I have function which search the network looking for my device and function which connect my client to the device. Moreover, I have function which takes lux value from my light sensor, using request to my server. Using that value, I want to steer my room bulb in Real Time. By that, I mean running client which use power and brigthness functions which will steer my room bulb (that algorytm isnt done yet) . I thought that setInterval Will be Best for that purpose but I am open to other solutions. Thanks for the help

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM