A
A
angelzzz2019-07-17 11:37:17
Node.js
angelzzz, 2019-07-17 11:37:17

How to emit from node.js through socket.io data from the response at intervals?

I need to make a "movie" (by "movie" I mean changing pages every N seconds) using JS.
I have an array of objects in node.js, using socket.io I want to emit (emit) the content of these objects every N seconds in React.
There is such an API endpoint:

router.get("/start/:handle", (req, res) => {
  Game
    .findOne({ url: req.params.handle })
    .then(game => {
      let questionList = [];
      game.blocks.map(block => {
        block.questions.map(question => {
          questionList.push(question)
        })
      })

      questionList.map(question => {
        return setInterval(
          res.status(200).send(question)
          , 5000);
      })
    })
    .catch(err => console.log("start game, err =>", err))
})

But it doesn't work. I get an error:
TypeError [ERR_INVALID_CALLBACK]: Callback must be a function

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2019-07-17
@angelzzz

It probably needs to be done in a different way. But I don't know how to do it

You will probably be very surprised now, but in order to connect using Socket.IO, you need to connect and use the Socket.IO library.
You can study the issue yourself at this link .
You have an error due to the incorrect use of setInterval, instead of a callback, you pass the result of the send execution there.
Instead of:
Must:
setInterval(() => {
  foo(bar);
}, duration);

Well, in order to be able to stop its execution, it must be stored and cleaned according to a certain condition:
const interval = setInterval(() => {
  foo(bar);
  if (someCondition()) {
    clearInterval(interval);
  }
}, duration);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question