javascript - 如果某个功能不起作用,则在一段时间后停止该功能

标签 javascript react-native

我有一个功能,允许使用蓝牙连接到外部设备。

有时可能是外部设备关闭或找不到设备的情况, 所以我的应用程序在搜索页面上崩溃(它卡在负载上)。我想知道是否有一种方法可以在函数执行30秒后发送警报。

   async scans() {
//connection...
// if the connection failed the checkCredentials will not execute, so there I should find something to display alert.
        this.checkCredentials()
    }

我想到了 setTimeout(() => {this.setState({time: true})}, 15000)

但我不确定这是最好的解决方案。

我该怎么办?

最佳答案

我认为您应该在启动连接之前首先尝试检查设备是否存在。然后,下一步您应该处理连接错误。您可以检查连接 API 是否提供了提供超时的方法。如果这一切都不可能,那么只有您应该尝试使用 setTimeout 来处理此问题,正如您在问题中提到的那样。但是在这种情况下,您还应该考虑取消连接请求或至少在连接最终失败时处理错误的情况。

关于javascript - 如果某个功能不起作用,则在一段时间后停止该功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58858893/

相关文章:

javascript - Node js/javascript : how to process streams sequentially with pipe and async/await when parsing csv and calling webservices with got?

javascript - 如何在javascript中对两个对象和数组进行映射

javascript - 如何将 HTML 链接定向到 R Shiny 中的侧边栏项目

javascript - 如何获取所有带有 "click"事件的元素与 jQuery 相关联?

javascript - Firebase 推送适用于 componentDidMount 而不是函数

javascript - 开 Jest 时出错 : The module factory of `jest.mock()` is not allowed to reference any out-of-scope variables

javascript - ReactJS中组件内部的函数

react-native - 尝试创建发布包时无法解析模块 'AccessibilityInfo'

ios - 如何修复 pod 安装错误 glog 太旧或缺少 Windows 10 中的 native ios

java - 无法在react-native模拟器上运行应用程序