---
title: "Socket.setTimeout( timeout ) | Grafana k6 documentation"
description: "Set socket inactivity timeout"
---

> For a curated documentation index, see [llms.txt](/llms.txt). For the complete documentation index, see [llms-full.txt](/llms-full.txt).

# Socket.setTimeout()

Sets the inactivity timeout for the socket. When the socket has been idle for `timeout` milliseconds without receiving data, a `timeout` event is emitted.

The socket *doesn’t automatically close* after a timeout. The connection remains open until you explicitly call `destroy()`. To disable a previously set timeout, pass `0`.

## Signature

JavaScript ![Copy code to clipboard](/media/images/icons/icon-copy-small-2.svg) Copy

```javascript
socket.setTimeout(timeout);
```

## Parameters

Expand table

| Parameter | Type   | Description                                             |
|-----------|--------|---------------------------------------------------------|
| timeout   | number | Inactivity timeout in milliseconds. Pass `0` to disable |

## Returns

Expand table

| Type   | Description                              |
|--------|------------------------------------------|
| Socket | The socket instance, for method chaining |

## Example

JavaScript ![Copy code to clipboard](/media/images/icons/icon-copy-small-2.svg) Copy

```javascript
import { Socket } from 'k6/x/tcp';

export default async function () {
  const socket = new Socket();

  const closed = new Promise((resolve) => {
    socket.on('close', () => {
      console.log('Connection closed');
      resolve();
    });
  });

  socket.on('data', (data) => {
    const str = new TextDecoder().decode(data);
    console.log('Received:', str);
    // Reset the timeout after each data event
    socket.setTimeout(5000);
  });

  socket.on('timeout', () => {
    console.log('No data received for 5 seconds — closing');
    socket.destroy();
  });

  socket.on('error', (err) => {
    console.error('Error:', err);
  });

  const host = __ENV.TCP_HOST || 'localhost';
  const port = __ENV.TCP_PORT || '8080';

  await socket.connect(port, host);
  console.log('Connected — waiting for data (5s timeout)');

  // Set timeout after connecting; no immediate write so the idle timer can fire
  socket.setTimeout(5000);

  await closed;
}
```
