0

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?

2
  • You want them to run in order? Commented Dec 10, 2016 at 21:24
  • yes, and if u can help, i need to do it by using a function which will go over the array of strings array={'string_1','string_2','string_3'} Commented Dec 11, 2016 at 1:30

1 Answer 1

1

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()
    }
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

o-o-okay, yes it helps. Thank u! But what if i need to display an array of strings, like array = [ 'ssssss', 'AAAAA', '11111' ]; so, i need to loop it in another function. but how 2 make it with a callback func?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.