-2

I want to show a welcome message simulating a write from keyboard. I try to do it like that, but I can't achieve it:

$(function(){
    $('h2').text(''); //delete the previous text
    var msg = 'Welcome'; //new text for the h2 element
    var phrase = '';

    for(var i=0; i<msg.length; i++){
        phrase += msg[i];
        $('h2').text(phrase).delay(10000);//here i want to pause 
    }
});
Guillermo Verón
  • 218
  • 1
  • 11
  • Something like this? https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval#Example_3_Typewriter_simulation – Anthony Mar 20 '18 at 18:24

1 Answers1

1

Use the function setTimeout to simulate that effect.

$(function() {
  $('h2').text(''); //delete the previous text
  
  function write(msg, phrase, index) {
    if (index == msg.length) return;
  
    phrase += msg[index];
    $('h2').text(phrase);
    
    setTimeout(function() {
      write(msg, phrase, ++index);
    }, 100);
  }
  
  var msg = 'Welcome'; //new text for the h2 element
  write(msg, '', 0);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2></h2>
Ele
  • 33,468
  • 7
  • 37
  • 75