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

查看:33
本文介绍了是否有必要在递归调用的计时器内清除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.

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

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