jQuery - setTimeout wait before continue by norlihazmey ghazali

http://stackoverflow.com/questions/35868647/display-text-in-input-field-letter-for-letter-with-delay/35868899?noredirect=1#comment59402617_35868899

by Norlihazmey Ghazali

HTML

<input type="text" class="input-group-field" size="50">

JavaScript

var arr = ['Hello, my name is john Doe', 'I love to code in JS', 'And what about you??'],
    inc = 0, 
    timingContainer = [], 
    ID;

function showLetter(field, text, delay, currentInc ) {
   var dfd = $.Deferred();
   ID = 0;
   inc = currentInc;
   currentInc++;
   
   $(field).val(text.substring(0, 1));
   
   for (var i = 2; i <= text.length; i++) {
   
      (function(i) {
      
        timingContainer.push( setTimeout(function() {

            if (i == text.length) {
               ID = setTimeout(function() {
                  // we sent the ID of setTimeout
                  // just in case to clear it out
                  // from executing
                  dfd.resolve([currentInc, ID]);
               }, delay);
            }

            $(field).val(text.substring(0, i));

         }, (delay = delay + 100)) );

      })(i)

   }

   dfd.done(function(data) {
      // if current index is more than
      // the length of array data that we have
      // then, we reset the counter
      // to start with index 0 of array
      if (data[0] > (arr.length - 1)) {
      	 data[0] = 0;
         inc = 0;
         //clearTimeout(data[1]);
         //return;
      }
      showLetter(".input-group-field", arr[data[0]], 100, data[0] )
   })
}
showLetter(".input-group-field", arr[0], 100, 0);

$('.input-group-field')
	.on('focus',function () {
    clearTimeout( ID );
    $( this ).val( ' ' );    
    for( var i = 0, length = timingContainer.length; i < length; i++ ) {
      clearTimeout( timingContainer[i] );
    }
	})
  .on('blur',function () {
    clearTimeout( ID );
    showLetter(".input-group-field", arr[inc], 100, inc );
	});