I am working on single page application, This application is realtime visualization for analytics.
AngularJs
Node.js
socket.io
I am having the following route in the application:
What i am doing using socket.io?
When i route to /activePage, I am triggering the activePage event from client side.
Server is listening to the particular event and it will fetch some data related to that event, send data to client by emitting some event with some time interval.
When i change to another route suppose /devicePage. It will follow as same as above with different event name.
Problem : client is getting two different data one for activePage and devicePage. I expected only one data that belongs to last route devicePage.
Server side Code:
socket.on("activePage", function (data) {
setInterval(function () {
realTime.getActivePageData(data, function (result) {
socket.volatile.emit("active", result);
});
}, 3000);
});
socket.on("devicePage", function (data) {
setInterval(function () {
realTime.getDeviceData(data, function (result) {
socket.volatile.emit("device", result);
});
}, 3000);
});
Client Side Code:
SocketService.on("active", function (data) {
console.log("active", data);
});
SocketService.on("device", function (data) {
console.log("device", data);
});
Note: This application is for multiple users.
How can i solve this issue?
Any suggestion will be grateful.
Seems like you start an interval on the "activePage" event, which repeatedly sends the 'active' data. Since you're not saving this interval into a variable, I assume it's not cleared anywhere else in the code.
One solution would be clearing the previous interval when you start a new one on a new event, something like this:
var activePageInterval; //this variable will hold the interval
socket.on("activePage", function (data) {
activePageInterval = setInterval(function () {
realTime.getActivePageData(data, function (result) {
socket.volatile.emit("active", result);
});
}, 3000);
});
socket.on("devicePage", function (data) {
clearInterval(activePageInterval); //clearing the interval to stop sending 'active' data
setInterval(function () {
realTime.getDeviceData(data, function (result) {
socket.volatile.emit("device", result);
});
}, 3000);
});
(and vica versa - you might as well use the same variable with a more generic name, since I assume you never want to have more than 1 type of data broadcasted regularly, just the one appropriate for the current page)