imsogrym imsogrym -4 years ago 94
Javascript Question

Add delay to JS animated text?

So I have the code below for a auto typing text animation. The text is in front of a image and I want people to see the full picture first and then the text starts to "type". I guess the best way is to add a 2-3 seconds delay before the text starts to animate but I'm not really sure how to do that.

Help would be very much appreciated. Thanks!

function cursorAnimation() {
$('#cursor').animate({
opacity: 0
}, 'fast', 'swing').animate({
opacity: 1
}, 'fast', 'swing');
}
$(document).ready(function() {
setInterval('cursorAnimation()', 1000);
});

var text = 'TEXT GOES HERE';

$.each(text.split(''), function(i, letter) {
setTimeout(function() {
$('#container').html($('#container').html() + letter);
}, 110 * i);
});

Answer Source

Adding some arbitrary delay is NOT the best way. You never know how much time an image will take to load on different kinds of networks, some are very fast, others might be very slow.

Instead you should fire your code on some event e.g. when the image has loaded. You can run your code on window load as an option as shown below:

function cursorAnimation() {
  $('#cursor').animate({
    opacity: 0
  }, 'fast', 'swing').animate({
    opacity: 1
  }, 'fast', 'swing');
}
$(document).ready(function() {
  setInterval('cursorAnimation()', 1000);

  $(window).on("load", function(){
    // do here tasks that you want to run after all page assets e.g. images have been loaded
    showText();
  });//window load()
});

function showText() {
  var text = 'TEXT GOES HERE';
  $.each(text.split(''), function(i, letter) {
    setTimeout(function() {
      $('#container').html($('#container').html() + letter);
    }, 110 * i);
  });
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download