The right way to use setTimeout in inifite loop Javascript


When we using setTimeout, actually it will assigned into some parameters with ID of task. To avoid memory leaks, we should comes with this strategy. First, declare global variable.

1
var timeOutClose;

Let say we have infinite loop function contains :

1
2
3
4
// Run timer to close box
timeOutClose = setTimeout(function() {
    $(".md-close").trigger("click");
}, animationClose * 1000);

Then we make sure to clear timeOutClose variable by put this before execution :

1
2
3
4
5
6
7
8
9
// Clear timeout                   
if (timeOutClose) {
   clearTimeout(timeOutClose);
}

// Run timer to close box
timeOutClose = setTimeout(function() {
    $(".md-close").trigger("click");
}, animationClose * 1000);

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.