我正在尝试使用一种方法创建一个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();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="body-window">
</div>
同
setTimeout(this.startTyping(index+1),5000);
你传递startTyping
的结果作为一个函数用setTimeout
调用 - 这是undefined
- 它也会立即调用,没有延迟。试试:
var that = this;
setTimeout(function() {
that.startTyping(index+1);
}, 5000);
改为:
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));
console.log(this.text.charAt(index))
setTimeout(() => this.startTyping(index+1), 500);
}
}
}
a = new autoWrite("body-window","hello world");
a.startTyping();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="body-window">
</div>
或者,您可以像这样使用setInterval()
(更好的方法):
class autoWrite{
constructor(id,text){
this.id = id;
this.text = text;
this.index = 0;
}
startTyping(){
if(this.index==this.text.length){
console.log("finish");
this.index += 1;
} else { $("#"+this.id).append(this.text.charAt(this.index));
console.log(this.text.charAt(this.index));
this.index += 1;
}
}
start(){
setInterval(() => {
if(this.index <= this.text.length){
this.startTyping();
}
}, 500);
}
}
a = new autoWrite("body-window","hello world");
a.start();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="body-window">
</div>
正如MDN here的setTimeout文档中所述,第一个参数是对延迟后需要执行的函数的引用。
您可以使用以下代码。
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));
let obj = this;
setTimeout(function () {
obj.startTyping(index+1);
},5000);
}
}
}
a = new autoWrite("body-window","hello world");
a.startTyping();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="body-window">
</div>