Search code examples
javascriptfunctionrecurrence

Let only one instance of the same function exists in Javascript


I have this onclick event listener on li items in a ul, that starts a setInterval function, the problem is if i click on a second li item another instance of the same intervalled function starts and the previous one keeps going. How can i "delete" the previous one and let only the last one to "exists"?

The solutions I found for the similar questions didn't work for me.

Here is the code:

document.addEventListener('click', function (event) {

  var texta = document.getElementById('myTextarea');

   var item = event.target.closest('#yourlists li');
   if (item) {
    var ite = event.target.closest('#yourlists li').innerHTML;

    setInterval(function autoSave(){
          var listText = texta.value.split('\n');
          localStorage.setItem(ite, JSON.stringify(listText));
    }, 5000);

   }
});

Solution

  • Use clearInterval. From docs,

    The clearInterval() method of the WindowOrWorkerGlobalScope mixin cancels a timed, repeating action which was previously established by a call to setInterval().

    var myInterval;
    
    document.addEventListener('click', function (event) {
         // ... code
        clearInterval(myInterval);
        myInterval = setInterval(function autoSave(){
          // ... code
        }, 5000);
        // ... code
    });