For循环不允许setTimeout执行 [英] For loop does not allow setTimeout to execute
问题描述
我具有下面的功能,该功能可以在给定的时间将一个字符记录在传递给该功能的句子中,看看下面的功能:
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);
如果我在上述程序I.E中添加一个for循环,则上述程序员现在可以正常工作了.
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 ?
为什么for循环不遵守 setTimeout
间隔?有人可以解释吗?
Why is it that the for loop does not honor the setTimeout
interval ? can anybody explain ?
推荐答案
如果您希望 timer
参数充当实际间隔,请使用以下方法:
If you want the timer
argument to act as an actual interval, use this:
function print_string(param, timer) {
for(var i = 0 ; i < param.length ; i++) {
setTimeout((function(char){
return function () {
console.log(char);
}
})(param.charAt(i)), timer * i);
}
}
var str = print_string("hey there , whats up , hows the weather in Manhatten" , 500);
这是小提琴.
您的困惑是for循环立即发生,或者在处理器允许的速度下发生.当 setTimeout
处理程序执行时,它的作用域与您可能期望的范围不同.作用域不再位于for循环内(因为发生在处理器的不同滴答声中),因此打印变量丢失了.为了解决这个问题,我使用了所谓的闭包.我正在动态构建一个函数,以打印所需的特定变量,并将其作为参数传递给 setTimeout
.
The confusion for you is that a for loop happens immediately, or as fast as the processor will allow it. When the setTimeout
handler executes, it has a different scope to what you're probably expecting. The scope is no longer within the for loop (because that happened in a different tick of the processor) so the print variable is lost. In order to get around this, I'm using what is called a closure. I'm building a function on the fly, to print the specific variable that I need, and passing it as an argument to setTimeout
.
在此处了解更多信息.
这篇关于For循环不允许setTimeout执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!