使用
setInterval()
肯定比
loop statement
,因为使用循环将阻塞JS的执行,并且您将无法在同一时间执行某些操作。为了避免这种情况,您可以使用基于字符串长度的变速(如您所做的),但IMO这不会提供良好的视觉体验。
我也建议你看看
typed.js
图书馆。(其他图书馆也可以完成同样的任务,但是我有这个图书馆的经验,而且它工作得很好!)
使用该库可以通过各种选项对任务进行更灵活的控制,为什么要重新发明轮子?
下面是一个示例片段
键入.js
:
var typed = null;
$("#dislay").click(function() {
if(typed != null)
typed.destroy();
var contentFromServer = "Smile spoke total few great had never their too. Amongst moments do in arrived at my replied. Fat weddings servants but man believed prospect. Companions understood is as especially pianoforte connection introduced. Nay newspaper can sportsman are admitting gentleman belonging his. Is oppose no he summer lovers twenty in. Not his difficulty boisterous surrounded bed. Seems folly if in given scale. Sex contented dependent conveying advantage can use. Do play they miss give so up. Words to up style of since world. We leaf to snug on no need. Way own uncommonly travelling now acceptance bed compliment solicitude. Dissimilar admiration so terminated no in contrasted it. Advantages entreaties mr he apartments do. Limits far yet turned highly repair parish talked six. Draw fond rank form nor the day eat. In post mean shot ye. There out her child sir his lived. Design at uneasy me season of branch on praise esteem. Abilities discourse believing consisted remaining to no. Mistaken no me denoting dashwood as screened. Whence or esteem easily he on. Dissuade husbands at of no if disposal.";
var typedOptions = {
strings: [contentFromServer],
typeSpeed: 60,
showCursor: false
};
typed = new Typed("#displayArea", typedOptions);
});
div {
border: 1px solid gray;
padding: 8px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/typed.js/2.0.8/typed.js"></script>
<button id="dislay" type="button">Display Content</button>
<div id="displayArea"></div>