zoukankan      html  css  js  c++  java
  • 计时器的内存泄露

    前言:这是一个很无聊的坑,但是不太容易去注意到。

    简述一下,通常使用计时器都要记得清除定时器,来避免造成内存泄露。

    上问题代码:

    1 let time = 0   
    2  this.timer = setInterval(() => {
    3       if (time <= 1) {
    4         time= time + 0.2
    5       } else {
    6         this.timer = null;
    7         clearInterval(this.timer);
    8       }
    9     }, 1000)

    上诉代码,貌似没问题,实际问题很大

    由于this.timer直接赋值为空后,clearInterval(this.time), 反而清除失败,而这种属于细节问题,平时代码不注意即可能出现。

    解决代码:

    1 let time = 0   
    2   this.timer = setInterval(() => {
    3        if (time <= 1) {
    4          time= time + 0.2
    5        } else {
    6        clearInterval(this.timer);

    7 this.timer = null;
    8  } 

    9 }, 1000)

    调整一下位置即可。

    以梦为马
  • 相关阅读:
    TS 3.1
    TS 3.1
    MDN 教程
    MDN 教程
    MDN 教程
    MDN 教程
    MDN 教程
    MDN 教程
    cookie会话技术
    数据库语法-1
  • 原文地址:https://www.cnblogs.com/lsAxy/p/14173795.html
Copyright © 2011-2022 走看看