简体   繁体   English

JavaScript 中 setInterval 中的函数

[英]Functions inside setInterval in JavaScript

I have a problem to call functions inside the setInterval function in JavaScript.我在 JavaScript 中调用 setInterval 函数内的函数时遇到问题。 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.该功能会关闭我房间的灯泡,并且在 setInterval 之外它也能正常工作。 Unfortunately, inside the setInterval it doesn't work at all.不幸的是,在 setInterval 中它根本不起作用。 Program never enters the function and for example print: Power off the device.程序永远不会进入该功能,例如打印:关闭设备电源。

How should I call that functions inside the setInterval?我应该如何在 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.不是每 3 秒一次。
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). 300-s 是转换时间(以毫秒为单位),首先它为设备通电,然后它尝试每 1.5 秒在 50% 和 100% 亮度之间切换(或多或少,内部超时不是很好,它宁愿使用状态变量代替)。

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.我认为 setInterval 最适合此目的,但我对其他解决方案持开放态度。 Thanks for the help谢谢您的帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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