For loop does not allow setTimeout to execute

前端 未结 4 1132
不知归路
不知归路 2021-01-22 05:00

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_st         


        
4条回答
  •  时光说笑
    2021-01-22 05:15

    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);
    

    Here is a fiddle.

    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.

    Read more about closures here.

提交回复
热议问题