0

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()
4

1 回答 1

1

您的代码在语法上无效。第 9 行在参数之间缺少逗号:

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

应该

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

提示:http ://coffeescript.org的“Try CoffeeScript”功能有一个内置的语法检查器,当它们没有按预期工作时,您可以使用它来仔细检查您的代码片段。

于 2013-09-02T15:42:00.697 回答