Home > other >  jQuery Typing effect stop loop
jQuery Typing effect stop loop

Time:11-04

I am trying to stop the loop at the last word "three" but it keeps looping and I can't figure it out how. Any solutions? thanks!

/*  
Type animation
*/

const words = ["one", "two" , "three"];
let i = 0;
let timer;

function typingEffect() {
    let word = words[i].split("");
    var loopTyping = function() {
        if (word.length > 0) {
            document.getElementById('word').innerHTML  = word.shift();
        } else {
            deletingEffect();
            return false;
        };
        timer = setTimeout(loopTyping, 300);
    };
    loopTyping();
};

function deletingEffect() {
    let word = words[i].split("");
    var loopDeleting = function() {
        if (word.length > 0) {
            word.pop();
            document.getElementById('word').innerHTML = word.join("");
        } else {
            if (words.length > (i   1)) {
                i  ;
            } else {
                i = 0;
            };
            typingEffect();
            return false;
        };
        timer = setTimeout(loopDeleting, 10);
    };
    loopDeleting();
};

typingEffect();

Here's the fiddle code: https://jsfiddle.net/al1225/w4rd65yx/

tried to debug the code but no luck on how to stop the loop.

CodePudding user response:

Put return false inside else condition when i = 0 on deletingEffect() function.

Working example:

/*  
Type animation
*/

const words = ["one", "two", "three"];
let i = 0;
let timer;
let flag = 0;

function typingEffect() {
  let word = words[i].split("");
  var loopTyping = function() {
    if (word.length > 0) {
      document.getElementById('word').innerHTML  = word.shift();
    } else {
      flag  
      if (flag < 3) {
        deletingEffect();
      }
      return false;
    };
    timer = setTimeout(loopTyping, 300);
  };
  loopTyping();


};

function deletingEffect() {
  let word = words[i].split("");
  var loopDeleting = function() {
    if (word.length > 0) {
      word.pop();
      document.getElementById('word').innerHTML = word.join("");
    } else {
      if (words.length > (i   1)) {
        i  ;
      } else {
        i = 0;
        return false;
      };
      typingEffect();
      return false;
    };
    timer = setTimeout(loopDeleting, 10);
  };
  loopDeleting();
};

typingEffect();
<h1  id="word"></h1>
<h1 >|</h1>

  • Related