是否有必要在递归调用的计时器中清除clearTimeout? [英] Is it necessary to clearTimeout inside a recursively invoked timer?

查看:255
本文介绍了是否有必要在递归调用的计时器中清除clearTimeout?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有必要在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.

这篇关于是否有必要在递归调用的计时器中清除clearTimeout?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆