Memory leak in jQuery AJAX calls

后端 未结 1 1499
梦谈多话
梦谈多话 2021-01-13 04:53

I\'ve written a little chat-box widget which runs an ajax call every second, to fetch new messages that have been posted. The problem is it\'s leaking memory, and after only

1条回答
  •  悲哀的现实
    2021-01-13 05:15

    Never use setInterval() with ajax, otherwise your requests never stay synchronized. Use setTimeout() instead and then pending your logic, initiate the setTimeout() recursively in the complete callback.

    Example.

    $(DoMyAjax); // start your ajax on DOM ready
    function DoMyAjax() {
       $.ajax({ 
          complete: function() {
              // your logic here
              setTimeout(DoMyAjax, 1000);
          }
       });
    }
    

    0 讨论(0)
提交回复
热议问题