Baz Baz - 3 months ago 18
Node.js Question

Delays in node.js server

How would you go about introducing a delay between the two emits below:

var app = require('http').createServer();
var io = require('socket.io')(app);

app.listen(8092);

io.on('connection', function (socket) {
socket.emit('foo', ["data1"]);
socket.emit('foo', ["data2"]);
});


I want to create a simple server simulator which outputs data at different points in time.

Answer

Have you tried this:

var app = require('http').createServer();
var io = require('socket.io')(app);

app.listen(8092);

io.on('connection', function(socket) {

  socket.emit('foo', ["data1"]);

  setTimeout(() => {
    socket.emit('foo', ["data2"]);
  }, 1500); // change the 1500 to whatever time delay you want in milliseconds
});

Reference: NodeJS timers