For loop does not allow setTimeout to execute

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

    I think you want something like this:

    var print_string = function ( param, interval ) {
      var
        i = 0,
        len = param.length,
        
        result = document.getElementById( 'result' ),
        
        // function called for every characters
        next = function () {
          // get the current character
          var char = param.charAt(i);
          
          // do what you want with them
          result.innerHTML += char;
          
          // if not the end of the string
          if ( ++i < len ) {
            // continue after the interval
            setTimeout( next, interval );
          }
        }
    
      next();
    }
    
    print_string( 'hey there , whats up , hows the weather in Manhatten!', 50 );

提交回复
热议问题