elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Recuerda que debes registrarte en el foro para poder participar (preguntar y responder)


+  Foro de elhacker.net
|-+  Programación
| |-+  Scripting
| | |-+  [JS] Encontrar la causa de la fuga de memoria en este Gadget
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: [JS] Encontrar la causa de la fuga de memoria en este Gadget  (Leído 2,545 veces)
Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.788



Ver Perfil
[JS] Encontrar la causa de la fuga de memoria en este Gadget
« en: 20 Diciembre 2014, 10:04 am »

Hola

A ver si alguien me puede prestar ayuda para encontrar una posible fuga de memoria en este script.

El código lo he sacado de este gadget para windows, y lo que hace es monitorizar el estado de los dispositivos conectados (el espacio libre de almacenamiento):
http://win7gadgets.com/pc-system/sushis_driveinfo.html

Creo que el problema está al dibujar las imágenes, la parte donde maneja los objetos de las imágenes, el cual bajo mi punto de vista parecen ser correctamente liberados en cada operación, aunque mi nivel de javascript es practicamente nulo, me guio por la sintaxis, así que quizás estoy omitiendo algo importante que no consigo ver, de hecho seguramente así espero que sea, ya que el tamaño no deja de incrementarse, si dejas el gadget corriendo 24 horas puede llegar a superar incluso el 1 GB de consumo de RAM, mientras que con otros gadgets del mismo tipo...esto no sucede, así que dudo que sea un problema del sidebar.exe, y no del Gadget.

Es horrible que el desarrollador de este Gadget no se haya dado cuenta de eso en +4 años de desarrollo y actualizaciones (este gadget es una re-version de un gadget anterior y con nombre parecido, del 2009 o 2010), espero que yo pueda hacer algo para arreglarlo, con vuestra ayuda.

sushi_driveinfo.html
Código
  1. <html>
  2.  <head>
  3.    <title>Drive Info</title>
  4.    <style>
  5.      body { margin: 0; padding: 0; width: 156px; height: 200px; background-image: url(images\canvas.png); color: #ffffff; font-family: 'Segoe UI'; }
  6.      #targets { position: absolute; top: 0; left: 0; }
  7.      .target { position: absolute; width: 156px; height: 48; left: 0; cursor: hand; }
  8.    </style>
  9.    <script type="text/javascript">
  10.      var lst = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  11.      var timeout = null;
  12.  var drives = new Array(26);
  13.  var drvchk = new Array(26);
  14.  var drvspc = new Array(26);
  15.  var vizchg = false;
  16.  var current_y = 0;
  17.  var background,theme,remove,local,network,media,show_pc,show_net;
  18.  var item_height=48;
  19.  var icon_offset=20;
  20.  var text_offset=72;
  21.  var meter_offset=24;
  22.  
  23.      function convertBytes(b)
  24.      {
  25.        var i = 0, u = Array(' MB', ' GB', ' TB');
  26.        while (b >= 1024 && (b /= 1024) >= 1) i++;
  27.        return (Math.round(b * 100) / 100) + u[i];
  28.      }
  29.  
  30.      function openDrive()
  31.      {        
  32.        var d = window.event.srcElement.getAttribute('drive');    
  33.        System.Shell.execute(d + ':\\');
  34. return;
  35.      }
  36.  
  37.  function openNetwork()
  38.      {        
  39.        System.Shell.execute("Explorer", "/N,::{F02C1A0D-BE21-4350-88B0-7367FC96EF3C}");
  40. return;
  41.      }
  42.  
  43.  function openComputer()
  44.      {        
  45.        System.Shell.execute("Explorer", "/N,::{20D04FE0-3AEA-1069-A2D8-08002B30309D}");
  46. return;
  47.      }
  48.  
  49.      function recheckDrives() {
  50.   for(var i = 0; i < 26; i++)
  51.        {
  52.  if (!drives[i]) {
  53.    drives[i] = System.Shell.drive(lst.charAt(i));
  54. if (drives[i]) { vizchg = true; drvchk[i] = true; }
  55.  } else {
  56.  if (drives[i].isReady != drvchk[i]) { drvchk[i] = !drvchk[i]; vizchg = true; }
  57.  if (drives[i].isReady && drives[i].freeSpace != drvspc[i]) { drvspc[i] = drives[i].freeSpace; vizchg = true; }
  58.  }
  59. }
  60.      }
  61.  
  62.      function calcHeight(h) {
  63.        var y=0;
  64.        if(show_pc==2) y+=h;
  65.        if(show_net==2) y+=h;
  66.        for(var i=0;i<26;i++)
  67.            if(isDriveVisible(i)) y+=h;
  68.        return y;
  69.      }
  70.  
  71.      function isDriveVisible(i) {
  72.        if(drvchk[i]) {
  73.           if      (drives[i].driveType == 2 && remove == 1)  ;
  74.           else if (drives[i].driveType == 3 && local == 1)   ;
  75.           else if (drives[i].driveType == 4 && network == 1) ;
  76.           else if (drives[i].driveType == 5 && media == 1)   ;
  77.           else if (drives[i].driveType == 1 || drives[i].driveType == 6) ;
  78.           else
  79.            return true;
  80.        }
  81.        return false;
  82.      }
  83.  
  84.      function paintPC() {
  85. if (show_pc == 2) {
  86. canvas.addImageObject('images/backgrounds/background' + background + 's.png', 0, current_y);  
  87. var di=canvas.addImageObject('images/drives/pc'+ theme +'.png', icon_offset, current_y);
  88.            di.width*=0.8;
  89.    di.height*=0.8;
  90. canvas.addTextObject('Computer', 'Segoe UI', 11, 'white', text_offset, current_y + 5);
  91. var b = document.createElement('DIV');
  92. b.className = 'target';
  93. b.style.posTop = current_y;
  94. b.onclick = openComputer;
  95. targets.appendChild(b);
  96. current_y+=item_height;
  97. }
  98.        return;
  99.      }
  100.  
  101.      function paintNET() {
  102. if (show_net == 2) {
  103. canvas.addImageObject('images/backgrounds/background' + background + 's.png', 0, current_y);  
  104. var di=canvas.addImageObject('images/drives/net'+ theme +'.png', icon_offset, current_y);
  105.            di.width*=0.8;
  106.    di.height*=0.8;
  107. canvas.addTextObject('Network', 'Segoe UI', 11, 'white', text_offset, current_y + 5);
  108. var b = document.createElement('DIV');
  109. b.className = 'target';
  110. b.style.posTop = current_y;
  111. b.onclick = openNetwork;
  112. targets.appendChild(b);
  113. current_y+=item_height;
  114. }
  115.        return;
  116.      }
  117.  
  118.      function paintGadget()
  119.      {  
  120.  try {
  121.        recheckDrives();
  122.        if (!vizchg) return;
  123.  
  124. var total_height=calcHeight(item_height);
  125. System.Gadget.beginTransition();
  126.  
  127. document.body.style.height=total_height;
  128. canvas.style.height=total_height;
  129. canvas.removeObjects();
  130. targets.innerHtml = '';
  131.  
  132. current_y = 0;
  133. paintPC();
  134. paintNET();
  135.        for(i = 0; i < 26; i++)
  136.        {
  137.            if(isDriveVisible(i)) {
  138.              if (drives[i].freeSpace != 0) {
  139.   canvas.addImageObject('images/backgrounds/background' + background + '.png', 0, current_y);  
  140.   var f = Math.round(drives[i].freeSpace / drives[i].totalSize * 100);
  141.               var u = (100 - f);
  142.   canvas.addTextObject(convertBytes(drives[i].freeSpace) + ' / ' + f + '%', 'Segoe UI', 10, 'white', text_offset, current_y + 17);
  143.   var m = canvas.addImageObject('images/meter' + (u < 90 ? 'blue': (u < 98 ? 'orange': 'red')) + '.png', meter_offset, current_y + 34);  
  144.       m.width = Math.floor((u * 128 / 100));
  145.               m.left = 24 - Math.floor(((128 - m.width) / 2));
  146.  } else {
  147.   canvas.addImageObject('images/backgrounds/background' + background + 's.png', 0, current_y);  
  148.   canvas.addTextObject(convertBytes(drives[i].totalSize), 'Segoe UI', 10, 'white', text_offset, current_y + 17);
  149.  }
  150.  
  151.  var di=canvas.addImageObject('images/drives/drive' + drives[i].driveType + theme + '.png', icon_offset, current_y-5);
  152.  di.width*=0.8;
  153.  di.height*=0.8;
  154.              canvas.addTextObject(drives[i].volumeLabel + ' (' + drives[i].driveLetter + ':)', 'Segoe UI', 11, 'white', text_offset, current_y + 5);
  155.              var o = document.createElement('DIV');
  156.              o.className = 'target';
  157.              o.style.posTop = current_y;
  158.              o.setAttribute('drive', drives[i].driveLetter);
  159.              o.onclick = openDrive;
  160.              targets.appendChild(o);
  161.  
  162.  current_y += item_height;
  163.   }
  164.        System.Gadget.endTransition(System.Gadget.TransitionType.morph,0.1);
  165.        window.setTimeout(fixCanvasBackground, 600);
  166.        }
  167. } finally {
  168. vizchg = false;
  169. return;
  170. }
  171.      }
  172.  
  173.  function fixCanvasBackground() {
  174. canvas.src = canvas.src;
  175.  }
  176.  
  177.      function initDrives()
  178.      {
  179.   for(var i = 0; i < 26; i++)  {
  180.    drives[i] = System.Shell.drive(lst.charAt(i));
  181. if (drives[i] && drives[i].isReady)
  182. { drvchk[i] = true ; drvspc[i] = drives[i].freeSpace; }
  183. else  { drvchk[i] = false; }
  184. }
  185. return;
  186.      }
  187.  
  188.  function onShowSettings() {
  189.    window.clearInterval(timeout);
  190. System.Gadget.beginTransition();
  191. window.setTimeout(endTransitionFast, 400);
  192.  }
  193.  
  194.  function onSettingsClosed() {
  195.    readSettings();
  196.    timeout=window.setInterval(paintGadget, 2500);
  197.    vizchg=true;
  198.    paintGadget();
  199.  }
  200.  
  201.  function endTransitionFast() {
  202. System.Gadget.endTransition(System.Gadget.TransitionType.morph, 0.1);
  203. fixCanvasBackground();
  204.  }
  205.  
  206.    function readSettings() {
  207.    background=System.Gadget.Settings.read("background");
  208.    if(background==0) { background=2; System.Gadget.Settings.write("background",2); }
  209.    theme=System.Gadget.Settings.read("theme");
  210.    if(theme==0) { theme=1; System.Gadget.Settings.write("theme",1); }
  211.    show_pc=System.Gadget.Settings.read("showpc");
  212.    if(show_pc==0) { show_pc=1; System.Gadget.Settings.write("showpc",1); }
  213.    show_net=System.Gadget.Settings.read("shownet");
  214.    if(show_net==0) { show_net=1; System.Gadget.Settings.write("shownet",1); }
  215.    local=System.Gadget.Settings.read("local");
  216.    if(local==0) { local=2; System.Gadget.Settings.write("local",2); }
  217.    media=System.Gadget.Settings.read("media");
  218.    if(media==0) { media=2; System.Gadget.Settings.write("media",2); }
  219.    network=System.Gadget.Settings.read("network");
  220.    if(network==0) { network=2; System.Gadget.Settings.write("network",2); }
  221.    remove=System.Gadget.Settings.read("remove");
  222.    if(remove==0) { remove=2; System.Gadget.Settings.write("remove",2); }
  223.  }
  224.  
  225.      function onLoad()
  226.      {
  227.        System.Gadget.settingsUI = "settings.html";
  228.        System.Gadget.onSettingsClosed = onSettingsClosed;
  229. System.Gadget.onShowSettings = onShowSettings;
  230.  
  231.        readSettings();
  232.        initDrives();
  233. timeout = window.setInterval(paintGadget, 2500);
  234. vizchg = true;
  235. paintGadget();
  236. return;
  237.      }
  238.    </script>
  239.  </head>
  240.  <body onload="onLoad()">
  241.    <div id="targets"></div>
  242.    <g:background id="canvas" src="images/canvas.png" style="position: absolute; top: 0; left: 0; width: 156; height: 200; z-index: -999;" opacity="0" />
  243.  </body>
  244. </html>

Luego está este otro html, pero por el nombre de los eventos y que además parece estar relacionado unicamente con la ventana de la configuración del gadget, es decir, que los eventos suceden muy esporádicamente o nunca... solo para dibujar el background de la ventana de configuración del gadget, entonces yo diría que poco o nada tiene que ver todo este código con la fuga:

settings.html
Código
  1. <html>
  2.  <head>
  3.    <style>
  4.      body { width: 250px; height: 800px; padding: 0px; margin: 0px; font-family: Tahoma; }
  5.      body,p,div,span,td { font-size: 9pt; }
  6.      label { font-weight: bold; }
  7.      input,select { font: Arial; font-size: 9pt; }
  8.      table { width: 100%; }
  9.    </style>
  10.    <script>
  11.      var background, maxBackgrounds = 3, theme = 1, maxThemes = 7;
  12.  
  13.      function updateBackground()
  14.      {
  15.        var x = 84, y = 47, m;
  16.        canvas.removeObjects();
  17.  
  18.        canvas.addImageObject('images/backgrounds/background' + background + '.png', x, y);
  19.        m = canvas.addImageObject('images/meterblue.png', x + 24, y + 34);  
  20.        m.width = (0.25 * 128);
  21.        m.left = x + 24 - ((128 - m.width) / 2);
  22.  
  23.        canvas.addImageObject('images/drives/drive3' + theme + '.png', x, y);
  24.        canvas.addTextObject('Vista (C:)', 'Segoe UI', 11, 'white', x + 58, y + 5);
  25.        canvas.addTextObject('40GB / 75%', 'Segoe UI', 10, 'white', x + 58, y + 17);
  26.  
  27.        //y -= 20;
  28.  
  29.        //canvas.addImageObject('images/backgrounds/background' + background + '.png', x, y);
  30.        //m = canvas.addImageObject('images/meterorange.png', x + 24, y + 34);  
  31.        //m.width = (0.937 * 128);
  32.        //m.left = x + 24 - ((128 - m.width) / 2);
  33.  
  34.        //canvas.addImageObject('images/drives/drive3.png', x, y);
  35.        //canvas.addTextObject('Apps (D:)', 'Segoe UI', 11, 'white', x + 58, y + 5);
  36.        //canvas.addTextObject('10GB / 6.3%', 'Segoe UI', 10, 'white', x + 58, y + 17);
  37.  
  38. canvas.addImageObject('images/drives/drive3' + theme + '.png', x-85, y+130);
  39. canvas.addImageObject('images/drives/drive2' + theme + '.png', x-85, y+172);
  40. canvas.addImageObject('images/drives/drive4' + theme + '.png', x-85, y+215);
  41. canvas.addImageObject('images/drives/drive5' + theme + '.png', x-85, y+258);
  42.      }
  43.  
  44.      function onBackground()
  45.      {
  46.        var e = window.event, o = e.srcElement, b = o.getAttribute('base');
  47.  
  48.        o.src = 'images/settings/' + b + (e.type == 'mouseover' || e.type == 'mouseup' ? 'hover': (e.type == 'mousedown' ? 'pressed': '')) + '.png';
  49.  
  50.        if (e.type == 'mouseup')
  51.        {
  52.          if (b == 'next') background++; else background--;
  53.          if (background < 1) background = maxBackgrounds;
  54.          if (background > maxBackgrounds) background = 1;
  55.  
  56.          updateBackground();        
  57.        }
  58.      }
  59.  
  60.  function onTheme()
  61.      {
  62.        var e = window.event, o = e.srcElement, b = o.getAttribute('base');
  63.  
  64.        o.src = 'images/settings/' + b + (e.type == 'mouseover' || e.type == 'mouseup' ? 'hover': (e.type == 'mousedown' ? 'pressed': '')) + '.png';
  65.  
  66.        if (e.type == 'mouseup')
  67.        {
  68.          if (b == 'next') theme++; else theme--;
  69.          if (theme < 1) theme = maxThemes;
  70.          if (theme > maxThemes) theme = 1;
  71.  
  72.          updateBackground();        
  73.        }
  74.      }
  75.  
  76.  
  77.      function onClose(event)
  78.      {
  79.        if (event.closeAction == event.Action.commit)
  80.        {
  81.          System.Gadget.Settings.write("background", background);
  82.  System.Gadget.Settings.write("theme",      theme);
  83.  System.Gadget.Settings.write("showpc",     document.boxes.mypc.checked ? 2 : 1);
  84.  System.Gadget.Settings.write("shownet",    document.boxes.netw.checked ? 2 : 1);
  85.  
  86.  System.Gadget.Settings.write("remove",     document.boxes.remove.checked ? 2 : 1);
  87.  System.Gadget.Settings.write("local",      document.boxes.local.checked ? 2 : 1);
  88.  System.Gadget.Settings.write("network",    document.boxes.network.checked ? 2 : 1);
  89.  System.Gadget.Settings.write("media",      document.boxes.media.checked ? 2 : 1);
  90.    }
  91.  
  92.        event.cancel = false;
  93.  
  94. // System.Gadget.beginTransition();
  95. // window.setTimeout(endtransit, 400);
  96.  }
  97.  
  98. /*  function endtransit() {
  99. System.Gadget.endTransition(System.Gadget.TransitionType.morph, 0.1);
  100.  }*/
  101.  
  102.  
  103.      function onLoad()
  104.      {
  105.    var box;
  106.        System.Gadget.onSettingsClosing = onClose;
  107.  
  108.        background = System.Gadget.Settings.read("background");
  109.        if (background == 0) background = 2;
  110.  
  111. theme = System.Gadget.Settings.read("theme");
  112.        if (theme == 0) theme = 1;
  113.  
  114. System.Gadget.Settings.read("remove")  == 2 ? document.boxes.remove.checked  = true : false;
  115. System.Gadget.Settings.read("local")   == 2 ? document.boxes.local.checked   = true : false;
  116. System.Gadget.Settings.read("network") == 2 ? document.boxes.network.checked = true : false;
  117. System.Gadget.Settings.read("media")   == 2 ? document.boxes.media.checked   = true : false;
  118.  
  119. System.Gadget.Settings.read("showpc")  == 2 ? document.boxes.mypc.checked   = true : false;
  120. System.Gadget.Settings.read("shownet") == 2 ? document.boxes.netw.checked   = true : false;
  121.  
  122.        updateBackground();
  123.      }
  124.    </script>
  125.  </head>
  126.  <body onload="onLoad()">
  127.    <g:background id="canvas" src="images/settings/desktop.png" style="position: absolute; left: 1; top: 1; z-index: -999;" />
  128.    <div style="position: absolute; left: 0; top: 147px;">
  129.      <table cellspacing="0" cellpadding="0">
  130.        <tr>
  131.          <td style="width: 33%; padding-right: 10px;" align="right"><img src="images/settings/previous.png" base="previous" style="cursor: hand;" onmouseover="onBackground();" onmouseout="onBackground();" onmousedown="onBackground();" onmouseup="onBackground();" /></td>
  132.          <td style="width: 33%;" align="center"><label>Backgrounds</label></td>
  133.          <td style="width: 33%; padding-left: 10px;" align="left"><img src="images/settings/next.png" base="next" style="cursor: hand;" onmouseover="onBackground();" onmouseout="onBackground();" onmousedown="onBackground();" onmouseup="onBackground();" /></td>
  134. </tr>
  135. <tr>
  136.  <td style="width: 33%; padding-right: 10px;" align="right"><img src="images/settings/previous.png" base="previous" style="cursor: hand;" onmouseover="onTheme();" onmouseout="onTheme();" onmousedown="onTheme();" onmouseup="onTheme();" /></td>
  137.          <td style="width: 33%;" align="center"><label>Icon Theme</label></td>
  138.          <td style="width: 33%; padding-left: 10px;" align="left"><img src="images/settings/next.png" base="next" style="cursor: hand;" onmouseover="onTheme();" onmouseout="onTheme();" onmousedown="onTheme();" onmouseup="onTheme();" /></td>
  139.        </tr>
  140.      </table>
  141.      <table cellspacing="0" cellpadding="0" style="margin-top: 15px;margin-left:60px;">
  142.        <tr><td>
  143.          <form name="boxes">
  144. <input type="checkbox" name="local">
  145. <font style="font-size: 8pt;">Local Drives</font><p>
  146. <input type="checkbox" name="remove">
  147. <font style="font-size: 8pt;">Removable Drives</font><p>
  148. <input type="checkbox" name="network">
  149. <font style="font-size: 8pt;">Network Drives</font><p>
  150. <input type="checkbox" name="media">
  151. <font style="font-size: 8pt;">Media Drives</font><p>
  152. <input type="checkbox" name="mypc">
  153. <font style="font-size: 8pt;">My Computer link</font><br>
  154. <input type="checkbox" name="netw">
  155. <font style="font-size: 8pt;">Network Link</font>
  156. </form>
  157.        </td></tr>
  158.      </table>
  159.    </div>
  160.  </body>
  161. </html>
  162.  


« Última modificación: 24 Diciembre 2014, 08:57 am por Eleкtro » En línea

Slikp

Desconectado Desconectado

Mensajes: 67


Ver Perfil
Re: [JS] Encontrar la causa de la fuga de memoria en este Gadget
« Respuesta #1 en: 22 Diciembre 2014, 16:36 pm »

- Buenas Eleкtro, lamento no serte de mucha ayuda solo paso por aqui para sugerirte lo siguiente. El gadget que muestras parece ser una aplicación de escritorio sin embargo su codigo esta basando por lo que muestras en mucho javascript no crees que seria mas conveniente exponer tu caso en el foro de Desarrollo Web y no aqui en el de Scripting, dado que javascript es un lenguaje que tiene mas orientación a ser usado en la web y así tal vez #!drvy, MinusFour, EFEX puedan ayudarte que he visto que ellos son los que tiene un mayor conocimiento de ese lenguaje.

- Saludos.


En línea

EFEX


Desconectado Desconectado

Mensajes: 1.171


"Dinero Facil"


Ver Perfil WWW
Re: [JS] Encontrar la causa de la fuga de memoria en este Gadget
« Respuesta #2 en: 22 Diciembre 2014, 17:34 pm »

Los gadgets se decontinuaron desde hace tiempo por eso ya no se actualizan mas..

https://technet.microsoft.com/library/security/2719662
https://www.youtube.com/watch?v=7uK8t0haGmU
En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.788



Ver Perfil
Re: [JS] Encontrar la causa de la fuga de memoria en este Gadget
« Respuesta #3 en: 24 Diciembre 2014, 09:08 am »

El gadget que muestras parece ser una aplicación de escritorio sin embargo su codigo esta basando por lo que muestras en mucho javascript no crees que seria mas conveniente exponer tu caso en el foro de Desarrollo Web y no aqui en el de Scripting, dado que javascript es un lenguaje que tiene mas orientación a ser usado en la web

Te agradezco el consejo, pero en mi opinión el desarrollo web no implica solo utilizar un lenguaje orientado a web (como JS), sino que el problema/código también esté orientado al uso Web, en este caso no es así, como bien dices es para una aplicación de escritorio, por eso lo he considerado más adecuado en la sección de Scripting, al ser JS un lenguaje de Scripting también.



Los gadgets se decontinuaron desde hace tiempo por eso ya no se actualizan mas..

https://technet.microsoft.com/library/security/2719662
https://www.youtube.com/watch?v=7uK8t0haGmU

Gracias por comentar, ¿pero que tendrá que ver eso con el problema y la pregunta? '¬¬ :P,
de todas formas yo los utilizo en Windows 8.1, la plataforma sigue siendo usable :P (aunque no directamente por parte de Microsoft, claro está).

Desktop gadgets and sidebar for Windows 8.1 | Winaero



Ya he solucionado el problema, bueno, mejor dicho me han ayudado a solucionarlo, ya que ni de lejos habría podido resolver yo solo este problema sin los conocimientos necesarios sobre este lenguaje, ya que además la raíz del problema se trataba de algo bastante interno.

Y como me temía desde un principio, es debido a malas prácticas de uso, a la programación descuidada por parte del autor.

El motivo del overflow y la solución:
Citar
The main loop of the Gadget looks like this:

Código
  1. function paintGadget() {
  2.    // repaint/rebuild all UI elelments
  3.    // remove all elements
  4.    targets.innerHtml = '';
  5.    // buildup
  6.     var o = document.createElement('DIV');
  7.     o.onclick = openDrive;
  8.     targets.appendChild(o);
  9. }
  10.  
  11. function openDrive() {
  12. }
  13.  
  14. window.setInterval(paintGadget, 2500);

which basically means: call paintGadget every 2.5 seconds, for ever

This should be fine if the javascript engine and its resources are garbage collected when they are no longer in any scope. And this where things might go wromg due to sloppy programming.

Based on the answer from user dsg we learn that eventlisteners are a root cause for garbage collection to fail.

To overcome this problem we have to replace the line 'targets.innerHtml = '';' in the function 'paintGadget' with an implementation that removes the eventhandlers on every element before removing the element it self, like so:

Código
  1. while(targets.firstChild) {
  2.    var ch = targets.firstChild;
  3.    ch.onclick = null;
  4.    targets.removeChild(ch);              
  5. }

Con ese pequeño y útil reemplazamiento, el gadget ha superado todas las espectativas, cuando antes en 48h podía llegar al 1 GB de consumo de RAM, ahora nunca pasa de los 15 mb.

Saludos!
« Última modificación: 24 Diciembre 2014, 09:13 am por Eleкtro » En línea

Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

Mensajes similares
Asunto Iniciado por Respuestas Vistas Último mensaje
Que efecto causa este comando de linux en una web?
GNU/Linux
gatocano 2 2,862 Último mensaje 16 Noviembre 2011, 22:49 pm
por gatocano
(SOLUCIONADO) Fuga de memória en una función :(
.NET (C#, VB.NET, ASP)
Eleкtro 9 5,836 Último mensaje 8 Agosto 2013, 18:13 pm
por Eleкtro
'Tempus fugit': este 'gadget' te dice exactamente cuánto te queda
Noticias
wolfbcn 0 1,231 Último mensaje 14 Octubre 2013, 02:53 am
por wolfbcn
Este gadget permite encontrar y pagar el aparcamiento desde tu móvil
Noticias
wolfbcn 0 1,429 Último mensaje 29 Septiembre 2015, 18:35 pm
por wolfbcn
Qué es una fuga de memoria RAM y cómo arreglarla
Noticias
wolfbcn 0 1,246 Último mensaje 30 Enero 2017, 21:32 pm
por wolfbcn
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines