最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Countdown Timer Broadcast with Socket.io and Node.js - Stack Overflow

programmeradmin8浏览0评论

I am building a new version of my app with Node.js. Below you will find my winner countdown, where the output of console.log(counter), needs to be broadcasted with Socket.io to all clients.

var counter = 10;
var WinnerCountdown = setInterval(function(){
  console.log(counter);
  counter--

  if (counter === 0) {
    console.log("Congratulations You WON!!");
    clearInterval(WinnerCountdown);
  }
}, 1000);

My Socket.IO code is as follows:

setInterval(() => {
  wss.clients.forEach((client) => {
    client.send(new Date().toTimeString());
  });
}, 1000);

What should I replace the new Date().toTimeString(), so that it will show the message of console.log instead?

I am building a new version of my app with Node.js. Below you will find my winner countdown, where the output of console.log(counter), needs to be broadcasted with Socket.io to all clients.

var counter = 10;
var WinnerCountdown = setInterval(function(){
  console.log(counter);
  counter--

  if (counter === 0) {
    console.log("Congratulations You WON!!");
    clearInterval(WinnerCountdown);
  }
}, 1000);

My Socket.IO code is as follows:

setInterval(() => {
  wss.clients.forEach((client) => {
    client.send(new Date().toTimeString());
  });
}, 1000);

What should I replace the new Date().toTimeString(), so that it will show the message of console.log instead?

Share Improve this question edited Aug 3, 2018 at 16:42 Rick 4,1249 gold badges27 silver badges37 bronze badges asked Feb 22, 2017 at 17:50 Exhibia AuctionsExhibia Auctions 191 gold badge1 silver badge3 bronze badges 1
  • I think you want to move the state (in this case counter) to the server-side code (the second snippet). Then the client-side can have zero logic other than to listen for an event from the server and console.log(result). – styfle Commented Feb 22, 2017 at 17:57
Add a ment  | 

1 Answer 1

Reset to default 4

To broad cast to all clients you can use io.sockets.emit('counter', counter);. Here is an example of a script you could use to achieve what (I think) you are trying to do:

server.js

io.on('connection', function(socket){
  var counter = 10;
  var WinnerCountdown = setInterval(function(){
    io.sockets.emit('counter', counter);
    counter--
    if (counter === 0) {
      io.sockets.emit('counter', "Congratulations You WON!!");
      clearInterval(WinnerCountdown);
    }
  }, 1000);
});

client.js

var socket = io();

socket.on('counter', function(count){
  $('#messages').append($('<li>').text(count));
});

Hope this helps, please ment if you have any follow up questions!

发布评论

评论列表(0)

  1. 暂无评论