setTimeout 遞歸,每 100ms 追加一個字元this 上下文與索引狀態var input_type = {
init: function($obj) {
this.chars = $obj.html().split("");
this.length = this.chars.length;
this.i = 0;
},
pri: function() {
var $this = this;
return (function next() {
if ($this.i >= $this.length) return;
$(".div1").append($this.chars[$this.i++]);
setTimeout(next, 100);
})();
}
};
function Input_type() { this.init.apply(this, arguments); }
Input_type.prototype = input_type;
// 使用
$(function() {
var p = new Input_type($(".content"));
p.pri();
});
<div class="content" style="display:none">這裡放要打字顯示的長文本...</div>
<div class="div1"></div> <!-- 顯示容器 -->
arguments.callee(已棄用)或具名函數 next() 實現遞歸this 避免 setTimeout 上下文丟失現代寫法可改用 async/await + Promise 更優雅。