jQuery Data Type How to - Use setTimeout to print a string char by char








Question

We would like to know how to use setTimeout to print a string char by char.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
window.onload=function(){<!--from w  w w  .ja  v a2  s  . com-->
  var message = document.getElementById("message");
  function writeMessage(string) {
      var i = 0, intervalId;
      intervalId = window.setInterval(function() {
          message.innerHTML += string.charAt(i++);
          if (i > string.length) 
              window.clearInterval(intervalId);
      }, 100);
    }
  writeMessage("Hello world");
}
</script>
</head>
<body>
  <div id="message" />
</body>
</html>

The code above is rendered as follows: