1

I'm trying to built a web-application which displays a dot on a map and update its position every 10seconds. The way I solved it right now is by polling a page via javascripts timeout every 10 seconds and parsing the result. This works fine, but when having multiple browsers polling the same webpage the webserver resources spike, obviously. Even when adding memcached as a intermediate.

My next thought was of instead polling the page with the latest positional information every 10 seconds, just create a open socket and send new data over it.

So after a search I stumbled upon socket.io which should do exactly what I want, but I'm not getting it to work.

Even a basic thing like the following doesn't work; it just show the hello world data in the console once. Instead of every second.... What is going wrong here?

server

var io = require('socket.io').listen(1332);
io.sockets.on('connection', function (socket) {

    setTimeout(function(){
        sentPosition(socket);
    }, 1000);
});

function sentPosition(socket){
    socket.emit('position', { 
            hello: 'world' 
        });
}

Browser

var socket = io.connect('http://myserver.com:8080');
socket.on('position', function (data) {
    console.log(data);
});
stUrb
  • 6,612
  • 8
  • 43
  • 71

1 Answers1

2

use javascript's setinterval method instead

Bijay Rai
  • 961
  • 1
  • 12
  • 32
  • setinterval doesn't seem to work for me when user goes out of the page and do something else. or if page is not focused, how can i execute my javascript even when page is not focused? @bijay – Faizan Nov 01 '19 at 18:36
  • @Faizan i think we can't control it from javascript if when page is not focused. But In case of react js, we used to have main wrapper which wraps all the pages in that case we can run setinterval again in main wrapper and all those changes we do can be store in redux store. – Bijay Rai Nov 03 '19 at 07:12