11

I have a node.js server and client. The client has a video.js player, progressbar.js and socket.io. I want progressbars to show buffer percentage of other users.

Here is piece of server source

function updateProgressBars() {
  io.sockets.emit('updateProgressBars'); //Send data to everyone
}

socket.on('userProgressBarUpdate',
  function(data) {
    socket.broadcast.emit('changeLocalProgressBar', data); //Send data to everyone but not sender
  });

And here is client

socket.on('updateProgressBars',
function() {
  var bufferLevel = myPlayer.bufferedPercent();
  var data = {
    bl: bufferLevel,
    n: name
  }

  socket.emit('userProgressBarUpdate', data); //Send data to server
});

changeLocalProgressBarLevel is just changing progressbars on client side so dont worry about it.

How can I make updateProgressBars() be called every second.

t.niese
  • 39,256
  • 9
  • 74
  • 101
  • 1
    Possible duplicate of [Calling a function every 60 seconds](https://stackoverflow.com/questions/3138756/calling-a-function-every-60-seconds) – t.niese Aug 18 '17 at 09:07
  • 1
    Possible duplicate of [socket.io setinterval way](https://stackoverflow.com/questions/9230647/socket-io-setinterval-way) – skymon Aug 18 '17 at 09:07

3 Answers3

12

You can use setInterval(function(){ ... }, timeMiliSeconds)

setInterval(function(){ console.log("hi")},1000) //logs hi every second
Nolyurn
  • 568
  • 4
  • 17
7

using setInterval is not the best choise because you should always clearInterval. I prefer using recursion with bluebird promises:

function a()
{
  if(smthCompleted)
    dosmth();
  else return Promise.delay(1000).then(() => a());
}

This way you have much better control of your code.

Jehy
  • 4,729
  • 1
  • 38
  • 55
  • What I miss in the usage of function a now.. There is an example for the rest of the world: `function run() { a().catch(() => console.log('error'))`. The run function calls the a function. And for every Promose `then` call, you should write a `catch`. – Melroy van den Berg Sep 14 '19 at 21:23
5

You can achieve this by using f.e. the "setInterval" function.

function doStuff() {
    //do Stuff here
}
setInterval(doStuff, 1000); //time is in ms

And even better:

let myVar = setInterval(function(){ timer() }, 1000);

function timer() {
//do stuff here
}

function stopFunction() {
    clearInterval(myVar);
}
Flocke
  • 1,004
  • 17
  • 23