简体   繁体   English

停止递归回调的最佳方法是什么?

[英]What's the best way to stop a recursive callback?

I'm trying to make an element shake, here is the code, with the jquery library 'jquery.transit'. 我正在尝试使用jquery库'jquery.transit'摇动元素,这是代码。

var s = $('myele');
var randomTran = function(){
    var rh = Math.floor((Math.random() * 10) - 5),
        rv = Math.floor((Math.random() * 10) - 5);
    s.transit({x:rh,y:rv},50,randomTran)
    }

The problem is the element will shake constantly, I need to put some stop sign to the recursive callback. 问题是元素会不断晃动,我需要在递归回调中添加一些停止符号。 What I can think of is to set a variable outside the function as a flag. 我能想到的是将函数外部的变量设置为标志。

var s = $('myele');
var flag = 0;
var randomTran = function(){
    if (flag<6) {
        var rh = Math.floor((Math.random() * 10) - 5),
        rv = Math.floor((Math.random() * 10) - 5);
        s.transit({x:rh,y:rv},50,randomTran)
    };
    flag++;
    }

But with this I smell the stench of global variable. 但是与此同时,我闻到了全局变量的恶臭。 So question 1 is there better way to do this? 那么问题1有更好的方法吗? Question 2: Is there any plugin that can make element shake? 问题2:是否有任何可以使元素动摇的插件?

You can do the same thing without a global: 您无需全局即可执行相同的操作:

var randomTran = function(flag){
  flag = flag || 0;
  if (flag<6) {
    var rh = Math.floor((Math.random() * 10) - 5),
        rv = Math.floor((Math.random() * 10) - 5);
    s.transit({x:rh,y:rv},50,randomTran.bind(this, ++flag))
  };
}

With the exception of s , this does not rely on any external variables and, as written, does not require you to modify any other code. 除了s ,这不依赖任何外部变量,并且按照编写,不需要修改任何其他代码。

Why make it global? 为什么要使其全球化? You can simply attach it to the s object. 您可以简单地将其附加到s对象。

var s = $('myele');
s.shakesLeft = 10;

var randomTran = function() {
    if (s.shakesLeft--) {
        var rh = Math.floor((Math.random() * 10) - 5),
            rv = Math.floor((Math.random() * 10) - 5);
        s.transit({x:rh,y:rv},50,randomTran)
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM