简体   繁体   中英

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'.

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? Question 2: Is there any plugin that can make element shake?

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.

Why make it global? You can simply attach it to the s object.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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