简体   繁体   English

React-native在指定的时间长度内运行函数

[英]React-native run a function for a specified length of time

I am writing a react native app that scans for bluetooth low energy devices. 我正在编写一个反应本机应用程序,用于扫描蓝牙低能耗设备。

I have a function, scan , which searches for devices, and a function stopScan , which stops the search. 我有一个函数scan来搜索设备,还有一个stopScan函数来停止搜索。 When the user presses the 'scan' button, I want this function to run for five seconds, and then stop and present the results. 当用户按下“扫描”按钮时,我希望此功能运行五秒钟,然后停止并显示结果。 Effectively I want something like this: 实际上,我想要这样的东西:

foo = () => {
    this.scan()
    //WAIT FIVE SECONDS
    this.stopScan()
}

I've looked at setTimeout etc, but I don't see how they solve the problem. 我看过setTimeout等,但看不到它们如何解决问题。 I'm also anxious to do this correctly, as I know that blocking the event loop can be problematic. 我也渴望正确地执行此操作,因为我知道阻止事件循环可能会出现问题。

Edit: 编辑:

  findDevices = () => {
      this.setState({ scannerStatus: "scanning" });
      this.scanAndConnect();
      setTimeout(this.manager.stopDeviceScan, 5000);
      this.setState({ scannerStatus: "scanned" });
  };

  scanAndConnect() {
    this.manager.startDeviceScan(null, null, (error, device) => {
      this.info("Scanning...");

      if (error) {
        console.log(error);
        this.manager.stopDeviceScan();
        this.error(error.message);
        return;
      }

      if (device.name === "foo") {
        this.info("Connecting to device");
        device
          .connect()
          .then(device => {
            this.info("Discovering services and characteristics");
            return device.discoverAllServicesAndCharacteristics();
          })
          .then(device => {
            this.info("Setting notifications");
            return this.setupNotifications(device);
          })
          .then(
            () => {
              this.info("Listening...");
            },
            error => {
              this.error(error.message);
            }
          );
      }
    });
  }

If you need to call the scan function in repetition for 5seconds you can do like this: 如果您需要重复调​​用scan函数5秒钟,可以执行以下操作:

 foo = () => {
      const scanInterval = setInterval(this.scan, 250) // It will call the scan function every 250ms

      setTimeout(() => {
        clearInterval(scanInterval)
        this.stopScan()
      }, 5000) // Stop the interval after 5s

    }

If you just need to call the stopScan() function after 5s, you can use a simple timeout: 如果只需要在5s之后调用stopScan()函数,则可以使用一个简单的超时:

foo = () => {
  this.scan()
  setTimeout(this.stopScan, 5000)
}

Which one you need to use depends on the actual implementation of scan() and stopScan() 您需要使用哪一个取决于scan()stopScan()的实际实现

EDIT: I have seen your code. 编辑:我看过您的代码。 The main issue is that setTimeout is NOT a blocking function. 主要问题是setTimeout不是阻塞函数。 It will NOT block the execution until the time has passed (ie 5second), but it will only execute the function you pass as first parameter after the delay. 在经过时间(即5秒)之前,它不会阻止执行,但只会执行延迟后作为第一个参数传递的功能。 So your code: 所以你的代码:

setTimeout(this.manager.stopDeviceScan, 5000);
this.setState({ scannerStatus: "scanned" });

will immediately set the scannerStatus to scanned, without waiting 5s. 将立即将scannerStatus设置为scannerStatus扫描,而无需等待5秒。 You need to set the call inside the timeout callback: 您需要在超时回调中设置呼叫:

setTimeout(() => {
   this.manager.stopDeviceScan();
   this.setState({ scannerStatus: "scanned" });
}, 5000);

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

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