NODEJS problem

C++, C#, Java, PHP, ect...
Post Reply
Robertt
Posts: 1
Joined: Fri Nov 08, 2013 12:08 pm

NODEJS problem

Post by Robertt »

Hello

I'm working with nodejs, what I have now is that it adds 1 second = +1.

What I want is if you jiont with a new browser that game will count where the other remained. So the other at 10 then the other also start at 10 and not at 0

My code:
app.js

Code: Select all

io.sockets.on('connection', function (socket) {  
	var counter = 0;
    	socket.on('testconnection', function() {
        	setInterval(function() {
           			var time =  counter++;
           			console.log(time);
					socket.emit('time', time);
       		}, 1000 );  
   	   });
 });
HTML

Code: Select all

  var socket = io.connect('http://localhost:8080');
  socket.emit('testconnection');

  socket.on('time', function(data){
        document.getElementById("demo").innerHTML= data;
    });
I hope if you can help me, I've tried console.log but I do not know how I can give console.log back. (socket.emit('time', (here consolelog);)

Sorry for bad english me, I'm a Dutchman who can english bad.
User avatar
Jackolantern
Posts: 10891
Joined: Wed Jul 01, 2009 11:00 pm

Re: NODEJS problem

Post by Jackolantern »

I am not sure if I follow what you want, but if that counter is actually supposed to count and hold the count, it needs to be moved out of all event handlers. It is going to be reset each time someone connects because you are using VAR, which re-initializes it.

As far as making the value show in the browser's console, you will have to use console.log() on the client-side. Node's console.log() is completely separate from the console.log() on the browser, even if they do have the same general effect.
The indelible lord of tl;dr
User avatar
hallsofvallhalla
Site Admin
Posts: 12023
Joined: Wed Apr 22, 2009 11:29 pm

Re: NODEJS problem

Post by hallsofvallhalla »

yep, you need to ove the setinterval outside of the sockets as you are setting the setInterval several times on the server which will eventually make it crap out. simply move this towards the top

var counter = 0;
setInterval(function() {counter++;});

if you want to reset the counter then put that inside of a socket. I however would not use this method in the end. I would store current time in a variable then when you need to check time just check time and minus the variable to get seconds passed. That way it is less burden on server.
Post Reply

Return to “Coding”