For loop does not allow setTimeout to execute

前端 未结 4 1137
不知归路
不知归路 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:38

    I'll try to exlain:

    You are passing a string with 30 characters to the function print_string so that the for loop will iterate and call setTimeout 30 times. After 50ms the first setTimeout callback will be called and will output the first char of your string. The variable strt_point will be incremented. Then the second setTimeout callback of your second for loop iteration will be called immediately and because strt_point is has already been incremented, the second char will be printed.

    The problem is that you have ONE variable strt_point for all iterations of the for loop so that all chars are printed after 50ms.

提交回复
热议问题