0

I have a css grid. When you click a div, it will toggle a class that makes it expand, then after 3000ms, the class is toggled again and the div collpases back to original size. The user should be able to over-ride this delay, so that if they want to collapse the div before the 3s setTimeout has elapsed, they can do it.

My issue is that when this happens, it doesn't cancel the set timeout function, and then the user input and the old 'lagging' code begin to overlap, which creates a mess and breaks my logic.

heres the code:

var open = false;

function dissolveExpand(parent, sibling, tte){
    if(open==false){
        open=true;
        toggle(parent, sibling, tte);
    } else{
        open=false;
        toggle(parent, sibling, tte);
    };
};

function closer(parent, sibling, tte){
    if(open==true){
        toggle(parent, sibling, tte);
    };
    console.log(open);
};

function toggle(parent, sibling, tte){
    parent.classList.toggle("expanded-div");
    sibling.classList.toggle("hidden-div");
    tte.classList.toggle("expanded-tap");
};

tte_parent1.onclick = function(){
    dissolveExpand(tte_parent1, sibling1, tte1);
    setTimeout(function(){closer(tte_parent1, sibling1, tte1); }, 3000);

};`

If I sit here and spam click the tte_parent element, the code just stops working properly.

Sorry for the lack of specifics but I'm stuck

anon
  • 159
  • 2
  • 3
  • 9
  • Might need to implement a [debounce](https://stackoverflow.com/questions/24004791/can-someone-explain-the-debounce-function-in-javascript) – Rainbow Jul 20 '19 at 14:28

2 Answers2

1

The clearTimeout() method clears a timer set with the setTimeout(). And instead of apply a true or false to the open variable, i would useisOpen = false , then isOpen = !isOpen every time it clicked

let isOpen = false;
let timeOut;

toggleClassList(){ 
  if(isOpen) {
     isOpen = !isOpen 
     //Remove expand class list logics 
     clearTimeOut(timeOut)
     return;
  } 
  isOpen = !isOpen 
  //Add expand class list logics go here
  timeOut = setTimeout(() => {
       isOpen = !isOpen
       //Remove class list after 3s
  }, 3000)
}
Web Dev
  • 13
  • 3
0

What you need to do is assign the setTimeout() call to a variable, because using setTimeout() returns a number unique to that call (like an id) which you can use to identify the timeout call when you want to clear it with clearTimeout(), an example below:

let timeOut = setTimeout(()=>console.log('this is a timeout'),3000);

clearTimeout(timeOut); // this cancels the timeout
Edmund1645
  • 309
  • 1
  • 2
  • 13