Javascript memory leak


Help me figure out what the clumsy code is. Perhaps it is not written rationally. When working in Google Chrome after 8-10 hours, terrible freezes and memory consumption begin.
The script receives data via Json, there is not a lot of data, and via ajax updates them with an interval of 5 seconds.

$(document).ready(function() {
    cache: false
  setTimeout(getData, 5000);

/* call the php that has the php array which is json_encoded */
function getData() {
  $.getJSON('api.php', function(data) {
    var d = new Date();
    var h = d.getHours();
    var m = d.getMinutes();
    var s = d.getSeconds();
    document.getElementById("time").innerHTML = +h + ":" + m + ":" + s;

    /* data will hold the php array as a javascript object */
    $.each(data, function(key, val) {
        '<tr><td><li id="' + key + '">' + + ' MSK' + /*' ' + val.event + */ 
        '</td><td>' + val.region.replace("POV", "<b><font color\=\"FireBrick\">POV</font></b>").replace("SZ", "<b><font color\=\"darkmagenta\">SZ</font></b>").replace("SIB", "<b><font color\=\"Olive\">SIB</font></b>").replace("UG", "<b><font color\=\"MidnightBlue\">UG</font></b>") + 
        '</td><td>' + + 
        '</td><td>' + val.type.replace("[", "<b>").replace("]", "</b>") + 
        '</td><td>' + + 
        '</td><td>' + val.status.replace("0", "<img src=\"green.png\">").replace("1", "<img src=\"red.png\">") + 
    setTimeout(getData, 5000);


jQuery is not memory-saving. When $('...').empty() is called, it is very likely that the child elements are not removed at all (for the browser) – so when there are a lot of iterations, it is better to use other ways of modifying the HTML.

Second, the page life of 8-10 hours is justified only when the user leaves the computer without closing the tab / browser and for a long time – browsers do not count on a different page life for 8-10 hours. Life means the activity of scripts, ajax requests, etc. That is, if the page is open, but the user is not active: stop scripts, there will be no leaks. Therefore, you can calculate the user's activity:

$(document).on('mousemove keyup',function(){
  window.lastActivity = (new Date).valueOf();

And if, for example, there was no activity for a minute, stop the activity of the interval:

function getData() {
   if ((new Date).valueOf() - window.lastActivity > 60*1000){
     setTimeout(getData, 1000);

Then, if the user "announces", the page will come to life no later than in a second. This is a simple example, it is more correct to take into account the focus / defocus of the window, the scroll event – but the approach is standard. For example, mobile browsers themselves stop the work of JS at the kernel level when the browser is minimized, when the tab is changed: there is no need to track activity there.

Scroll to Top