[web-bluetooth] How to properly abort a `device.gatt.connect()` attempt (#640)

mgibbs189 has just created a new issue for https://github.com/WebBluetoothCG/web-bluetooth:

== How to properly abort a `device.gatt.connect()` attempt ==
Hello,

Could someone please describe the "correct" way to handle a failed reconnection attempt?

When `gattserverdisconnected` fires, I want to try reconnecting for up to 30 seconds, then abort. This seems like a common use-case.

```js
let device, server;
let timeout;

let timeoutPromise = new Promise((_, reject) => {
    timeout = setTimeout(() => reject(new Error('Connection timeout')), 30000);
});

try {
    server = await Promise.race([device.gatt.connect(), timeoutPromise]);
    // successfully reconnected, do other stuff
}
catch(err) {
    // failed to reconnect, how to abort connect()?
    // this often causes `navigator.bluetooth.requestDevice()` to stop responding, perhaps
    // because the browser is still actively trying to connect?
}
finally {
    clearTimeout(timeout);
}
```

It'd be super helpful if someone could clarify what happens with `connect` behind the scenes...

* Is there actually a way to abort `device.gatt.connect()`?
* Is there any browser-level timeout? Or, will a `connect()` run indefinitely (i.e. the lifetime of the pageload)?
* What does `gatt.device.disconnect()` do, when a device is disconnected/dropout, or when a `connect()` is running for that device?

Thanks

Please view or discuss this issue at https://github.com/WebBluetoothCG/web-bluetooth/issues/640 using your GitHub account


-- 
Sent via github-notify-ml as configured in https://github.com/w3c/github-notify-ml-config

Received on Thursday, 23 January 2025 02:53:25 UTC