title: socket.send outside of io.sockets.on( )
body: <p>I have a loop that querys a database continuously. When the query returns a result, the node.js app will send a message to every client connected to the node server via socket.io v0.8.</p>
  
  <p><strong>Problem:</strong> <code>io.sockets.broadcast.send('msg')</code> is called in the middle of a <code>setInterval()</code> loop so it is not within an <code>io.sockets.on()</code>'s callback function and thus this will not work. When <code>io.sockets.send('msg')</code> is used, no message seems to be sent to the client.</p>
  
  <p><strong>Node.js code</strong></p>
  
  <pre><code>setInterval(function() {
      util.log('Checking for new jobs...');
      dbCheckQueue(function(results) {
          if (results.length) {
              io.sockets.broadcast.send('hello');
          }
      });
  }, 10*1000);
  </code></pre>
  
  <p>However, if the <code>setInterval</code> is to be called from within <code>io.sockets.on('connection',..)</code>, every connected client will create an additional loop!</p>
  
  <p><strong>Node.js code</strong></p>
  
  <pre><code>io.sockets.on('connection', function(socket) {
      setInterval(function() {
          util.log('Checking for new jobs...');
          dbCheckQueue(function(results) {
              if (results.length) {
                  io.sockets.send('hello');
              }
          });
      }, 10*1000);
  });
  </code></pre>
  
  <p><strong>Clientside JS</strong></p>
  
  <pre><code>        socket.on('hello', function() {
              console.log('HELLO received');
          })
  </code></pre>
  
  <p>*How can I get a SINGLE loop to run, but still be able to send a message to all connected clients?</p>