setTimeout的递归方法

KaS*_*uLL 1 javascript jquery settimeout

我正在尝试使用一种方法创建一个js对象,该方法将逐字母打印,每个字母之间有5秒的延迟.但是现在还没有运行.它毫不拖延地写出来.我的错误在哪里?

class autoWrite{
    constructor(id,text){
        this.id = id;
        this.text = text;
    }
    startTyping(index=0){
        if(index==this.text.length){
            console.log("finish");
        }
        else{
            $("#"+this.id).append(this.text.charAt(index));
            setTimeout(this.startTyping(index+1),5000);
        }
    }
}
 a = new autoWrite("body-window","hello world");
 a.startTyping();
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
 <div id="body-window">

</div>
Run Code Online (Sandbox Code Playgroud)

hsz*_*hsz 5

setTimeout(this.startTyping(index+1),5000);
Run Code Online (Sandbox Code Playgroud)

你传递的结果startTyping作为一个函数被调用setTimeout- 也就是说undefined- 它也会立即被调用而没有延迟.试试:

var that = this;
setTimeout(function() {
  that.startTyping(index+1);
}, 5000);
Run Code Online (Sandbox Code Playgroud)