Existe Deja
Existe Deja

Reputation: 1379

Coffeescript : setInterval, clearInterval and anonymous function

I use setInterval() into an anonymous function and I want to use clearInterval() in another anonymous function. I'm using socket.io and I need to have intervalID for each socket, so I can't use global variable.

I can clearInterval when clearLoops() is fired into the setInterval loop, but it doesn't work in my other socket events.

io.sockets.on 'connection', (socket) ->
  intervalID = -1

  clearLoops = ->
     if intervalID != -1
       clearInterval intervalID
       intervalID = -1

  socket.on 'first:action', (data, callback) ->
    myArray = data
    setTimeout(->
      intervalID = setInterval(->
        arrLength = myArray.length
        if arrLength is 0
          clearLoops()
        while i < arrLength
          if myArray[i].score >= MAX_SCORE
            myArray.splice i, 1
            i--
            arrLength--
          i++
      , 300)
    , 3000)


  socket.on 'second:action', ->
    clearLoops()


  socket.on 'disconnect', ->
    clearLoops()

Upvotes: 0

Views: 936

Answers (1)

Matt Ball
Matt Ball

Reputation: 360046

Your code is not syntactically valid. Line 9 is missing a comma between parameters:

 socket.on 'first:action' (data, callback) ->

should be

 socket.on 'first:action', (data, callback) ->

Hint: http://coffeescript.org's "Try CoffeeScript" feature has a built-in syntax checker which you can use to double-check your code snippets when they're not working as expected.

Upvotes: 1

Related Questions