Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

110
Visualizações
Conflict between 2 websockets

I've been trying to create a script which shows Bitcoin and Ethereum price according to users preference. So if an user clicks on bitcoin button it shows bitcoin price and when user clicks on Ethereum button it shows Ethereum.

Everything kind of works but when you click on Bitcoin button and then on Ethereum button it creates a conflict and keeps switching between Bitcoin and Ethereum price.

I have tried to use

pricesWs1.close(); and pricesWs.close(); but it completely closes 1 websocket and you can't swap between the prices.

Javascript

const pricesWs = new WebSocket('wss://ws.coincap.io/prices?assets=bitcoin')
 const pricesWs1 = new WebSocket('wss://ws.coincap.io/prices?assets=ethereum')  
 
 $(document).ready(function() {
    $('.buttonbtc').click(function(e) {  

pricesWs.onmessage = function (msg) {

        var str = msg.data                                      
    var matches = str.match (/\b\d+(?:.\d+)?/);
    var finalprice = parseFloat(matches);
     document.getElementById("btc").innerHTML = finalprice;
     
}

   });
});

 $(document).ready(function() {
    $('.buttoneth').click(function(e) {  
    
pricesWs1.onmessage = function (msgg) {
    
    var str = msgg.data                                      
    var matches = str.match (/\b\d+(?:.\d+)?/);
    var finalprice = parseFloat(matches);
    document.getElementById("btc").innerHTML = finalprice;
}

   });
});

LIVE DEMO: https://jsfiddle.net/s9rv1agu/

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

The problem seems to be that you're getting constant response messages from the coinbase server. You can prevent the text display from being updated onmessage unless the socket that sent it matches the last clicked button.

In this case I stored the value of the last clicked button in a variable named cp and only update the display on message if it was sent by the corresponding socket.

Code:

    const pricesWs = new WebSocket('wss://ws.coincap.io/prices?assets=bitcoin')
     const pricesWs1 = new WebSocket('wss://ws.coincap.io/prices?assets=ethereum');
     
     var cp = -1;//current_price
     
     $(document).ready(function() {
        $('.buttonbtc').click(function(e) {  
    
     cp = 0;
     document.getElementById("btc").innerHTML = "pending...";
    pricesWs.onmessage = function (msg) {
    
         if(cp == 0) {
            var str = msg.data                                      
        var matches = str.match (/\b\d+(?:.\d+)?/);
        var finalprice = parseFloat(matches);
         document.getElementById("btc").innerHTML = finalprice;
    }
         
    }
    
       });
    });
    
    
     $(document).ready(function() {
        $('.buttoneth').click(function(e) {  
        
    cp = 1;
    document.getElementById("btc").innerHTML = "pending...";
    pricesWs1.onmessage = function (msgg) {
        if(cp == 1) {
        var str = msgg.data                                      
        var matches = str.match (/\b\d+(?:.\d+)?/);
        var finalprice = parseFloat(matches);
    
        document.getElementById("btc").innerHTML = finalprice;
        }
    }
    
       });
    });

If you however also want to stop the root cause of the problem(the constant messages being sent by the server) you will need to iniate the socket connection and close the connection after a message (or possibly some configuration with coinbase which will only send back 1 message).

var pricesWs;
var pricesWs1;

const wlist = ['wss://ws.coincap.io/prices?assets=bitcoin',
             'wss://ws.coincap.io/prices?assets=ethereum'];
 
 var cp = -1;//current_price
 
 $(document).ready(function() {
    $('.buttonbtc').click(function(e) {  

 cp = 0;
 document.getElementById("btc").innerHTML = "pending...";
 pricesWs = new WebSocket(wlist[0]);
  pricesWs.onopen = function() {
pricesWs.onmessage = function (msg) {

     if(cp == 0) {
        var str = msg.data                                      
    var matches = str.match (/\b\d+(?:.\d+)?/);
    var finalprice = parseFloat(matches);
     document.getElementById("btc").innerHTML = finalprice;
}
     pricesWs.close();
}
}

   });
});


 $(document).ready(function() {
    $('.buttoneth').click(function(e) {  
    
cp = 1;
document.getElementById("btc").innerHTML = "pending...";
 pricesWs1 = new WebSocket(wlist[1]);
 pricesWs1.onopen = function() {
pricesWs1.onmessage = function (msgg) {
    if(cp == 1) {
    var str = msgg.data                                      
    var matches = str.match (/\b\d+(?:.\d+)?/);
    var finalprice = parseFloat(matches);

    document.getElementById("btc").innerHTML = finalprice;
        }
    pricesWs1.close();
    }
}

   });
});

an additional check can also be added to ensure the sockets are not in the process of being opened when a button is clicked

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda