简体   繁体   中英

jquery the functions sequence

I wrote the function Animal(), which displays text strings character by character:

var j=0;//counter derived fields 
var flag= -1;//Animal() performance indicator

function Animal(string) {
    flag=1;
    console.log('flag start:', flag );
    var a = ''; //The variable which will be entered character by character string
    var i= 0;
    var p = document.createElement('p');
    $('body').append(p);

    Anima();

    flag=0;
    console.log('flag end: ', flag);    
    //
    //
    function Anima() {  
        console.log('string start: ', j);
        a=a+string[i];
        i++;
        $('p:eq('+j+')').text(a);
        var timer = setTimeout(Anima, 100);
        if(i==string.length){
            clearTimeout(timer);
            j++;
            console.log('end: ', j);

        };
    };

Animal('dfkjdghksjdfhglksd');
Animal('11111111');

When I call function Animal() second time, it starts working, while first Animal() is working. How to make it works consistently?

Explanation

It works in such way because Animal calls setTimeout which in result runs Anima asynchronously and makes it possible to run second instance of Animal concurrently.

Possible solution

One option is to add a second parameter to the Animal function that's a callback to function that should be run when the first is done.

Animal('dfkjdghksjdfhglksd', function () {
  Animal('11111111');
});

And implementation:

function Animal(string, callback) {
  flag=1;
  console.log('flag start:', flag );
  var a = ''; //The variable which will be entered character by character string
  var i= 0;
  var p = document.createElement('p');
  $('body').append(p);

  Anima();

  flag=0;
  console.log('flag end: ', flag);    
  //
  //
  function Anima() {  
    console.log('string start: ', j);
    a=a+string[i];
    i++;
    $('p:eq('+j+')').text(a);
    var timer = setTimeout(Anima, 100);
    if (i==string.length) {
      clearTimeout(timer);
      j++;
      console.log('end: ', j);
      callback(); // here we run next Animal()
    }
  }
}

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