stackmember
stackmember

Reputation: 23

Why does the socket.on function gets repeated?

My programs works like this: When I click dice in index.html, it starts happy() function in javascript file, which signals to generate the random number in app.js. This random number is then received by the javascript file and then randomNum() is called. My problem: When I open the html file and then click the dice, it is good. But, when I again click on the dice, I found out that the socket.on of the happy() function was repeated twice. Again, when I clicked the dice, the socket.on was repeated three times and so on. What is going on? I am just getting started on node.js, so any help would be appreciated. My codes: Dice in index.html

<div id="dice" onclick="happy()" style="background-image:url(/client/Images/dice.gif)"></div>

Javascript file

var num1 = [];

var socket = io();
function happy(){
        console.log(num1);
        num1 = [];
        socket.emit('happy',{
            reason:true
        });
        
        socket.on('rannumber',function(data){
            console.log(data.reason);
            if(0< data.reason <7){
                num1.push(data.reason);
                randomNum();
            }
        });
}

app.js file

var io = require('socket.io')(serv,{});
io.sockets.on('connection', function(socket){ 
    console.log('socket connection');
        
    socket.on('happy', function(data){
        console.log(data.reason);
        if (data.reason = true){
            console.log('generating random number')
            var number = Math.floor((Math.random() * 6) + 1);
            socket.emit('rannumber',{
                reason: number
                
            });
            console.log(number)
        }
    });
    
});

Upvotes: 2

Views: 204

Answers (1)

Rahul Bhobe
Rahul Bhobe

Reputation: 4451

You need to move this outside the happy() function:

        socket.on('rannumber',function(data){
            console.log(data.reason);
            if(0< data.reason <7){
                num1.push(data.reason);
                randomNum();
            }
        });

Currently every time happy() function is called a new callback is registered for socket.on('rannumber', ...). So, whenever rannumber is emitted, each of those registered callbacks will be called. You need to register this callback only once.

You can try this:

var num1 = [];

var socket = io();

socket.on('rannumber',function(data){
    console.log(data.reason);
    if(0< data.reason <7) {
        num1.push(data.reason);
        randomNum();
    }
});

function happy(){
    console.log(num1);
    num1 = [];
    socket.emit('happy',{
        reason:true
    });
}

Upvotes: 1

Related Questions