Question

What my app do:

  1. Streams information asynchronously (It's a comet style app and im using Faye).
  2. Appending to a carrousel.
  3. Displaying it for 7 secs.
  4. Repeating the step (2).

What my problem is: If i append the data to the carrousel right in the moment that arrives it will overwrite the current display (ignoring the 7 secs).

What i am doing: Trying to build a 'waiting line' in coffeescript so when the new data arrives it gets in line and after 7 secs the first element on the line pop it and append. I tried to use setTimeout but it didn't work because it is asych.

An example:

line = []
# the second parameter is the callback function when a new data arrives
faye.subscribe 'my/channel/', (data) -> 
  appendEl = (el) ->
    $('.my-container').append(el)
    line.slice(0,1)
  line.push(data)
  # I think this could work if timeout could block, like sleep()
  # So when new data arrives it will get in line
  my_time = setTimeout(appendData(data), 7000)
  if line.empty?
    clearTimeout(my_time)

I dont know if it is the best approach, this is my first app that streams live data.

Was it helpful?

Solution

There is two things you can do to do something many times with intervals.

  • use setTimeout with function, which will call setTimeout for itself

  • use setInterval with the function

What about your problem you just need to add some variable in the outer scope and use it, something like

var pipe = []

faye.subscribe('my/channel', function(data) {
   pipe.push(data)
})


setTimeout(appendData, 7000)

function appendData() {
   if (pipe.length) {
      var item = pipe.shift()
      $('.my-container').append(...)
   }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top