是否有必要在递归调用的计时器内清除Timeout?

是否有必要在 Coffeescript 的递归调用函数中调用 clearTimeout() ?

Is it necessary to call clearTimeout() inside a recursively invoked function in Coffeescript?

我担心的是,如果这个函数每秒运行很多次,不调用 clearTimeout() 是否会随着时间的推移导致某种内存泄漏.我的想法是 JS 垃圾收集器处理这个,但想仔细检查.

My concern is whether not calling clearTimeout() will possibly cause some sort of memory leak over time if this function is run many many times per second. My thinking is the JS garbage collector handles this, but want to double check.

我正在研究的 websockets/socket.io 实现中的人为示例:

A contrived example from a websockets/socket.io implementation I'm working on:

socket.on 'dataReceived', => @_recursive_fn()

_recursive_fn: ->
  @timer = setTimeout (=>
    clearTimeout(@timer) # is this necessary?
    @_recursive_fn() if some_condition == true
  ), 30

推荐答案

不,setTimeout 安排一次性事件.事件发生后,带有该句柄的 clearTimeout 将成为空操作.

No, setTimeout schedules a one-off event. Once the event has occurred, clearTimeout with that handle is a no-op.

相关文章