sending a message from client while connected to Websocket server in JavaScript

i’m using “ws” package of npm in order to connect to coinex websocket server.
i know that in onOpen function of ws i can send messages to server, but i want to be able to send messages after connecting to server. here is my code:

import WebSocket from 'ws';
import { URL } from 'url';
import { setTimeout } from "timers/promises";


class CoinexWebsocketClient{
    websocket: WebSocket;
    url: string|URL;
    constructor(url: string|URL){
        this.url = url;
    }
    connect(){
        this.websocket = new WebSocket(this.url);
        this.websocket.on('message', this.onMessage);
        this.websocket.on('close', this.onClose);
        this.websocket.on('open', this.onOpen);
        this.websocket.on('error', this.onError);
    }
    onError = (err)=>{
        console.log(err)
    }
    onOpen = ()=>{
        console.log('Connected to server');
        this.websocket.send(JSON.stringify({
            "method":"state.subscribe",
            "params":[
            "BTCUSD"
            ],
            "id":15
            })
        );
    }
    onClose = ()=>{
        console.log('Disconnected from server');
    }
    disconnect(){
        this.websocket.terminate();
    }
    onMessage=(message: string)=>{
        console.log(`Received message from server: ${message}`);
    }
    send(message){
        this.websocket.send(JSON.stringify(message))
    }
    
}

const customFunction = async (coinexWebsocket:CoinexWebsocketClient) => {
    await setTimeout(5000);
    console.log("Waited 5s");
  
    await setTimeout(5000);
    console.log("Waited an additional 5s");
    csws.send(JSON.stringify({
        "method":"kline.subscribe",
        "params":[
          "BTCUSD",
          60
        ],
        "id": 5
      }))
};
let csws = new CoinexWebsocketClient("wss://perpetual.coinex.com/")
csws.connect()
customFunction(csws)

but after timeout reaches and customFunction executes csws.send, my connection gets closed immediately. i want my client be connected to server and send messages using send function while code is running . how can i solve this issue?