防止函数调用,直到标志设置为真

问题描述:

我已经创建了非常容易的画廊。元素得到他们的变换位置或增加使用防止函数调用,直到标志设置为真

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); 
} 

一切正常下降的点击,但问题是,当我点击XXX时间RLY快,它就会被摧毁,确实不受欢迎的行为。我使用标志,因此只有当“running”为false时才能调用该函数,当应该移动的最后一个元素的转换结束时,我会返回false。它在最初的几次点击中都能正常工作,但快速点击会将其破坏并破坏整个脚本。

直播demo(点击RLY快速XXX次看到的行为)

这是什么原因?该标志只在转换结束时才被设置,为什么函数被调用?有没有办法如何解决它,或者我应该使用暴力(承诺)呢?

+0

几件事我注意到了蝙蝠是removeEventListener采用事件类型和回调,而不仅仅是回调。其次,您需要将侦听器绑定到对象以确保对象中的“this”是您的想法。检查出http://*.com/questions/1338599/the-value-of-this-within-the-handler-using-addeventlistener – karina

这似乎是你的问题:

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