递归可防止函数连续多次单击

时间:2016-04-01 20:22:29

标签: javascript css recursion

我使用递归创建了一个简单的脚本,以改变图像的位置。

它遍历它们并调整它们的位置,脚本是相对简单的代码:

var img = document.getElementsByClassName("container")[0];
 var X = 0;
 var Y = 0;
 var check;

 function all() {
   var decko = img.children;
   for (var i = 0; i < decko.length; i++) {
     if (i !== 0 && i % 3 === 0) {
       X = 0;
       Y++;
     }
     decko[i].style.transform = "translate3d(" + X * 100 + "px," + Y * 100 + "px,0)";
     X++;
   }
   X = 0;
   Y = 0;
   check = false;
 }
 all()

 window.onclick = function() {


   pushIt(img.length, img.children, 0, 0)

 }

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

   if (count == max) {
     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]-100;
   tmp.style.transform = "translate3d(" + translate_left + "px," + translate_top + "px,0)";
     setTimeout(function(){
        pushIt(max, target, index + 1, count + 1);
     },150)


 }

Here你可以看到它是如何运作的。问题是当有很多图像时。

当我点击调用该函数时,它会遍历所有图像(在我的情况下为30 +)。如果我在一秒钟内单击两次,它将循环遍历所有图像,然后它将执行第二次功能,这在我的情况下是不需要的行为(看起来很迟钝)。有什么方法可以防止这种行为吗?我选择了递归,bcs这似乎是最简单的选择。

1 个答案:

答案 0 :(得分:1)

如果您的JavaScript出现了一些错误,那么您有一对错误,即您的函数中未定义max。我有这个工作HERE

var img = document.getElementsByClassName("container")[0];
var decko = img.children;
var X = 0;
var Y = 0;
var check;
var running = false;

function all() {
    for (var i = 0; i < decko.length; i++) {
        if (i !== 0 && i % 3 === 0) {
            X = 0;
            Y++;
        }
        decko[i].style.transform = "translate3d(" + X * 100 + "px," + Y * 100 + "px,0)";
        X++;
    }
    X = 0;
    Y = 0;
    check = false;
}
all()

window.onclick = function () {

    if (!running) {
        running = true;
        pushIt(decko.length, img.children, 0, 0);
    }
}

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

    if (count == max) {
        running = 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] - 100;
    tmp.style.transform = "translate3d(" + translate_left + "px," + translate_top + "px,0)";
    setTimeout(function () {
        console.log(running);
        pushIt(max, target, index + 1, count + 1);
    }, 150)
}