jQuery Data Type How to - Print a string one character at a time with timed intervals








Question

We would like to know how to print a string one character at a time with timed intervals.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
window.onload=function(){<!--from  w  w w  . j  a v  a  2s .c o  m-->
function doWithInterval(id, sentence)
{
    var f;
    f= function(i){
        document.getElementById(id).innerHTML+=sentence[i];
        if(i+1==sentence.length)
           return;
        window.setTimeout(function(){f(i+1);},500);
    }
    f(0);
}
doWithInterval('input','this is a test');
}
</script>
</head>
<body>
  <div id='input'></div>
</body>
</html>

The code above is rendered as follows: