Increment value each time the function is called

Hi,
What I’m trying to do is that each time the function is called (when a message is received from the server), a variable is incremented by 1 from 49. Why? To create a new div for the new message.

Right now, i only return 50 each time, which is not what I want
How the function is called:

ws.onmessage = function(event){
        let newMessage = event.data;
        let messageRecopie = JSON.parse(newMessage);
        messageRecu(messageRecopie);
    };

And how I tried to increase i each time:

function messageRecu(obj){
    let chatMessage = obj;
    let i = (function(n){
            n += 1;
            return n;
    }(49));
    console.log(i);

    let chatWindow = document.getElementById('chat');
    let ligneChat = document.createElement('DIV');
    ligneChat.setAttribute('id','ligneChat'+i);
    chatWindow.appendChild(ligneChat);
(...)

The above executes the function you wrapped in ( and ) and calls it with the value you specified in the () which is 49. The function returns the value of the argument passed (49) plus 1. That is why when you console.log it, it shows 50.

Which variable are you wanting to increment? Right now, it is just incrementing the variable i.

If you can show how you create ws, I might be able to recommend a way to initialize a way to track the number of times the method is called.

I want to increment i each time a new message is received starting from 50 to infinite.
I don’t know if this is what you want, but ws is declared like this:

function connectionWebSocket(token){
    let ws = new WebSocket("ws://message.com:8000/ws");
...
ws.onmessage = function(event){
        let newMessage = event.data;
        let messageRecopie = JSON.parse(newMessage);
        messageRecu(messageRecopie);
    };
...

Why not create a variable inside the connectionWebSocket function to track the count and increment it inside the messageRecu function. This assumes the messageRecu is defined inside of connectionWebSocket.

Could you show me a brief example of what you mean? And also, messageRecu isn’t inside connectionWebSocket, but I guess I could move it.

let messageCount = 50;

This would go inside the connectionWebSocket function. Without seeing the entire code for your project, I can only suggested moving messageRecu inside connectionWebSocket. Where else outside of connectionWebSocket would you even call messageRecu, since ws lives inside connectionWebSocket?

You’re right, I was making it more difficult than it really was, thanks you!