0

So, I have this strange problem: First, I connect to a socket like this:

window.GLOBAL_socket = io.connect('http://localhost:8080');

Then, if I print out the window.GLOBAL_socket variable, I get a circular variable which contains the property 'connected' which is set true if the connection is succesfull, and false if it isn't as seen in the google chrome console. But when I write the following:

console.log(window.GLOBAL_socket.connected);

It always returns 'false'. Anyone has a clue why this doesn't change? (same happens with the property 'disconnect'; changes when I print out the entire variable, but stays 'true' when printing out the property.

Kind regards,

Zeno

2
  • By write the following do you mean write it in your source file or in google chrome console? Commented May 24, 2015 at 13:05
  • What is a "circular variable"? Commented May 24, 2015 at 15:18

1 Answer 1

1

The problem is that you're printing it out too early. It's not connected yet. Therefore what you printed out is correct - it's not connected.

The reason it works form the console is because by the time you type in the console it's already connected.

To prove this, print it out at a later time:

setTimeout(function(){
    console.log(window.GLOBAL_socket.connected);
},5000); // hopefully 5 seconds is long enough to connect
         // adjust this as necessary

Or you can keep logging until it's connected:

var connect_check = setInterval(function(){
    console.log(window.GLOBAL_socket.connected);
    if (window.GLOBAL_socket.connected) {
        clearInterval(connect_check);
    }
},10); // do this 100 times per second

Another way to execute a function at a later time is to attach it to an onclick event:

<button id="log">Log Connected Status</button>
<script>
    document.getElementById('log').onclick = function(){
        console.log(window.GLOBAL_socket.connected);
    };
</script>

Of course, you can simply use socket.io connection event:

GLOBAL_socket.on('connection',function(){
    // But then the following is redundant because we KNOW
    // it's connected because we're in this event handler.
    console.log(window.GLOBAL_socket.connected);
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.