The overall goal of this is to achieve a typing-like animation for some text. I'm looping through each letter of a string and adding it to the DOM with delays between each letter, using setTimeout
within a FOR loop.
My HTML--
<h1 id="name">Hello World!</h1>
My Javascript--
$(document).ready(function(){
var typeText = $("#name").html();
var textLength = typeText.length;
$("#name").empty();
for(i=0;i<textLength;i++) {
(function(i){
console.log("first function being fired!");
setTimeout(function(i){
console.log("setTimeout function being fired!");
console.log(i);
var letter = typeText.substring(i,i+1);
console.log(letter);
$("#name").append(letter);
},5000);
})();
}
});
I don't get any errors, but I am logged first with 12 accounts of "first function being fired!", a 5 second delay, then 12 accounts of this:
setTimeout function being fired<br />
undefined<br />
[line-break]
I think I'm missing a fundamental part of FOR loops, or don't completely understand how functions are handled within them.
You're not passing a value to your inner i
s.
$(document).ready(function(){
var typeText = $("#name").html();
var textLength = typeText.length;
$("#name").empty();
for(i=0;i<textLength;i++) {
(function(i){
console.log("first function being fired!");
setTimeout(function(){ // not necessary here
console.log("setTimeout function being fired!");
console.log(i);
var letter = typeText.substring(i,i+1);
console.log(letter);
$("#name").append(letter);
},5000);
})(i); // pass here
}
});
And if you want each to fire 5 seconds after the previous, instead of just waiting 5 seconds and doing all of them, you can set the timeout like that:
setTimeout(function(){
// ...
}, 5000 * i);
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments