Sam Chahine
Sam Chahine

Reputation: 620

Simulating typing with jQuery, pausing or lengthening the setInterval function

So I want to make a jQuery app where text is being animated on the screen to look as if someone is typing something. I've achieved this in its most simplest form.

HTML

<p></p>

jQuery

$(document).ready(function() {
    var p = $('p');
    p.text('');


    window.setInterval(function(){
        inc(p);
    }, 100);

});

var i = 0;

function inc(p)
{

    var text = "Hey... This is just a test";
    p.append(text.charAt(i));
    i++;
}

What I want to know is, how would I maybe after "Hey ..." tell the function to stop for 2 seconds? Or however many I want it to.

I had an idea but it's very inefficient and "crappy", and that is to add as many whitespaces as it would take to print nothing for 2 seconds, then replace the string with everything before the whitespace and continue appending.

This is terrible and I'd like a better way of doing it. Could anyone please give me any suggestions? And is setInterval the correct function to use or should I utilize setTimeout?

Here's a fiddle of my code.

I appreciate any help or suggestions, thank you very much.

Upvotes: 0

Views: 86

Answers (2)

Pierre C.
Pierre C.

Reputation: 1430

I guess there is a better way to do this but I'm posting my working answer.

I have replaced you setInterval by a setTimeout inside your inc function. So it is now recursive.

And you can change the interval when a certain character is typed by checking the index.

EDIT :

After OP comment I changed my answer so you can set delay inside the text using embraces.

$(document).ready(function() {
    var p = $('p');
    p.text('');

    inc(p);
});

var i = 0;
var j = 0;

function inc(p) {
  var interval = 0.1;
  var text = "Hey... {2} This is a {1} test";
  var array = text.split(/[\{\}]/); // Split on embraces
  
  if (i < array.length) {
    p.append(array[i].charAt(j));
    
    if (j == array[i].length -1 && typeof array[i + 1] !== "undefined") {
      interval = array[i + 1];
      i += 2;
      j = 0;
    }
    
    j++;
    setTimeout(function () { inc(p); }, interval*1000);
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p></p>

Upvotes: 1

Shayan
Shayan

Reputation: 966

try this, jsFiddle

$(document).ready(function() {
    var $p = $('p');
    $p.text('');
    waitFun($p);  
});
var timer;
var wait_time=2000;
var wait_point=7;
var count=0;
function waitFun($p){
  clearTimeout(timer);
    timer = window.setTimeout(function(){
  var text = "Hey... This is just a test";
    $p.append(text.charAt(count));
    count++;
  if(text.length == count) {return false} //avoid of infinte loop

  if(count == wait_point){
    window.setTimeout(function(){
        waitFun($p);
    },wait_time);
  }else{
  waitFun($p);
  }

  },100);

}

Upvotes: 0

Related Questions