I would like to emit a message to the client every X seconds until the client clicks a button and acknowledges receipt.
Any ideas on how I might accomplish this? New to Node but I am hoping I can get this done with Node and Sockets.io.
Thanks in advance for any insight or help to get me in the right direction.
I think the best way to accomplish this would be to create a new class that extends the "vanilla" Node.js event class. You will need to require it first like so:
const EventEmitter = require('events');
class MyEmitter extends EventEmitter {}
https://nodejs.org/api/events.html
Once you've got your class, what you will need to do is creating a child process, to do so, you can refer to the official documentation here:
https://nodejs.org/api/child_process.html
Inside this process you can create your loop and send a message through the socket. The goal of extending the events class is to be able to create an Inside event emission which you can listen to detect specific events (like socket closed, or anything you'd like to track)
I hope this answers your question.
This is a simple setup just to give you an idea of how to do it:
node server (very basic, only socket.io, nothing else):
const io = require('socket.io')(3000);
const interval = 1000;
io.on('connection', function (socket) {
console.log(socket.id + ' has connected');
var foo = setInterval (function () {
socket.emit('foo');
}, interval);
socket.on('confirmed', function () {
console.log('confirmation received from ' + socket.id);
clearInterval(foo);
});
});
console.log('socket.io server started at port 3000');
index.html (open it in your browser and see what happens):
<!doctype html>
<html>
<head>
<title>Testing socket.io</title>
</head>
<body>
<button id="button">Confirm</button>
<p id="socket">waiting...</p>
<p id="alert">foos counter: </p>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.7.3/socket.io.min.js"></script>
<script>
var socket = io("http://localhost:3000");
var counter;
socket.on('connect', function() {
counter = 0;
document.getElementById("socket").innerHTML = "connected";
document.getElementById("button").addEventListener("click", function () {
socket.emit("confirmed");
});
});
socket.on('foo', function() {
counter++;
document.getElementById("alert").innerHTML = "foos counter: " + counter;
});
</script>
</body>
</html>