seanlevan
seanlevan

Reputation: 1415

JavaScript typewriter script not working

Well basically I tried to make a typewriter script from scratch, for my little terminal web app junkie xD

Well, I've got this JavaScript thingy:

var str = "dude";
var num = 1000;
for (var i = 0, len = str.length; i < len; i++) {
var num = num + 100;
var dude = str[i];
setTimeout('document.getElementById("guide").innerHTML +=dude;', num);
}

which obviously writes to a div with the ID guide, "d" "u" "d" "e" in 100 milisecond intervals, but guess what ?

It doesn't do that !!

NOW what it DOES do it print "e" as many times as they are characters in the string, dude!!

:|

Thank you,

I'm probably super stupid

but I'd love a fix!

Thanks in advance!

Upvotes: 1

Views: 432

Answers (2)

Thomas Durieux
Thomas Durieux

Reputation: 476

I wrote a small function that accept 2 parameters: the text and the time :

function defiredWriteText(text,time, index){
    if(index === null || index === undefined) {
        index=0;
    }
    setTimeout(function (){
        var dude = text[index];
        document.getElementById("guide").innerHTML += dude;
        if(index < text.length-1)
            defiredWriteText(text, time, ++index);
    }, time)
}

sample: http://jsfiddle.net/3e3yx/

Upvotes: 1

Kyle Weller
Kyle Weller

Reputation: 2623

You might want to call a function in setTimeout like the following:

var str = "dude";
var num = 1000;
for (var i = 0, len = str.length; i < len; i++) {
  var num = num + 100;
  var dude = str[i];
  setTimeout(function() {
    document.getElementById("guide").innerHTML +=dude;
  }, num);
}

or

var str = "dude";
var num = 1000;
for (var i = 0, len = str.length; i < len; i++) {
  var num = num + 100;
  var dude = str[i];
  setTimeout(changeHtml, num);
}

function changeHtml() {
  document.getElementById("guide").innerHTML +=dude;
}

If you want a more precise 100 millisecond interval you might want to use setInterval

var myInterval = setInterval(changeHtml, 100);
var len = str.length;
var current = 0;

function changeHtml() {
  if(current < len) {
    document.getElementById("guide").innerHTML +=str[current];
  }
  else {
    clearInterval(myInterval);
  }
  current++;
}

Upvotes: 1

Related Questions