Menu

This is documentation for the next version of K6. For the latest stable release, go to the latest version.

Documentationbreadcrumb arrow Grafana k6breadcrumb arrow JavaScript APIbreadcrumb arrow k6/wsbreadcrumb arrow Socketbreadcrumb arrow Socket.setInterval(callback, interval)
Open source

Socket.setInterval(callback, interval)

Note

A module with a better and standard API exists.

The new k6/experimental/websockets API partially implements the WebSockets API living standard.

When possible, we recommend using the new API. It uses a global event loop for consistency with other k6 APIs and better performance.

Call a function repeatedly, while the WebSocket connection is open.

ParameterTypeDescription
callbackfunctionThe function to call every interval milliseconds.
intervalnumberThe number of milliseconds between two calls to callback.

Example

JavaScript
import ws from 'k6/ws';
import { check } from 'k6';

export default function () {
  const url = 'ws://echo.websocket.org';
  const params = { tags: { my_tag: 'hello' } };

  const res = ws.connect(url, params, function (socket) {
    socket.on('open', function open() {
      console.log('connected');

      socket.setInterval(function timeout() {
        socket.ping();
        console.log('Pinging every 1sec (setInterval test)');
      }, 1000);
    });

    socket.on('pong', function () {
      console.log('PONG!');
    });
  });

  check(res, { 'status is 101': (r) => r && r.status === 101 });
}