防止自定义 jquery 函数在同时运行时合并加入

Preventing a custom jquery function from merging joining when running at the same time

我正在尝试编写一个简单的 jquery "addon" 来为我打字,就像打字机一样。
这是我到目前为止想出的:

jQuery.fn.typer=function(speed){
  typed = this;
  theText = typed.text().split('');
  typed.text("");
  $.each(theText, function(index, value){
    setTimeout(function(){
      typed.append(value);
    },speed*index);
  });
  return;
};


$("#p0").typer(50);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id='p0'>This text will appear at the speed: 50</p>

在我尝试让它一次输入两个句子之前,它工作得很好。

jQuery.fn.typer=function(speed){
  typed = this;
  theText = typed.text().split('');
  typed.text("");
  $.each(theText, function(index, value){
    setTimeout(function(){
      typed.append(value);
    },speed*index);
  });
  return;
};


$("#p0").typer(50);
$("#p1").typer(100);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id='p0'>This text will appear at the speed: 50</p><br />
<p id='p1'>This text will appear at the speed: 100</p>

我得到的结果是:TThihs itesxt wtiel xaptpe arw ait lthle spaeepd:p 5e0ar at the speed: 100

关于如何阻止这种情况发生的任何线索?
提前致谢。

在不使用 var 关键字的情况下声明变量会将变量置于全局范围内。参见 this question for more details
因此,这两个实例共享变量并导致您在上面看到的乱码。

jQuery.fn.typer=function(speed){
  var typed = this;
  var theText = typed.text().split('');
  typed.text("");
  $.each(theText, function(index, value){
    setTimeout(function(){
      typed.append(value);
    },speed*index);
  });
  return;
};


$("#p0").typer(50);
$("#p1").typer(100);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id='p0'>This text will appear at the speed: 50</p><br />
<p id='p1'>This text will appear at the speed: 100</p>