I have the below function that logs a character in a sentence passed to a function at a certain given time, have a look at the function below:
function print_string(param , timer) {
var strt_point = 0,
str_len = param.length,
self = this;
//typewritter();
typeit();
function typeit() {
setTimeout(function(){
console.log(param.substring(strt_point).charAt(0));
if(strt_point < str_len ) {
strt_point++;
typeit()
}
} , timer);
}
}
var str = print_string("hey there , whats up , hows the weather in Manhatten" , 50);
console.log(str);
The above programmer works fine, now if i add a for loop to the above programme I.E. WRAP THE setTimeout in a for loop ,
function print_string(param , timer) {
var strt_point = 0,
str_len = param.length,
self = this;
for(var i = 0 ; i < str_len ; i++) {
//typewritter();
typeit();
function typeit() {
setTimeout(function(){
console.log(param.substring(strt_point).charAt(0));
if(strt_point < str_len ) {
strt_point++;
typeit()
}
} , timer);
}
}
var str = print_string("hey there , whats up , hows the weather in Manhatten" , 50);
console.log(str);
All the characters are printed at once , Why ?
Why is it that the for loop does not honor the setTimeout
interval ? can anybody explain ?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…