Darlyn
Darlyn

Reputation: 4938

Prevent function from invoking until flag get set to true

I have created pretty easy gallery. The elements gets their transform position increased or decreased on click using

 function pushIt(max, target, index, count) {

    if (count == max ) {
      target[index -1].addEventListener("transitionend",turnOf,false);
      return;
   }

   var tmp                  = target[index];
   var matrix               = window.getComputedStyle(tmp).getPropertyValue("transform");
   var translate_left       = matrix.split(",")[4];
   var translate_top        = matrix.split(",")[5].split(")")[0]-215;
   tmp.style.transform      = "translate3d(" + translate_left + "px," + translate_top + "px,0)";
   setTimeout(function(){
    pushIt( max, target, index + 1, count + 1 );
   },50)
 } 
function turnOf(){
  running = false;
  this.removeEventListener(turnOf);
 }

Everything is working fine , but the problem is , when i click xxx time rly fast , it gets destroyed and does unwanted behavior. I am using flag, so the function can be called only when "running" is false , which i return back to false when the transition of the last element that should be moved is over. It works on the first few clicks , but fast clicking ruins it and break whole script.

Live demo ( click rly fast xxx times to see the behavior )

What could cause this? The flag is only set only when the transition ends, so why the function gets invoked ? Is there a way how to fix it , or shoud i use brute force ( promises ) for this?

Upvotes: 0

Views: 36

Answers (1)

DIEGO CARRASCAL
DIEGO CARRASCAL

Reputation: 2129

This seems to be your problem:

function turnOf(){
  running = false;
  //this.removeEventListener(turnOf);
  this.removeEventListener("transitionend", turnOf);
 }

Upvotes: 1

Related Questions