2017-10-10 54 views
0

我正在尝试编写脚本来模拟实时输入。我已经制作了一个循环来每个0.15s放置每个字符,但是它同时给了我所有的文本。我应该使用递归,或者做一些像“睡眠”功能?Java脚本实时输入

var text = "Lorem ipsum dolor sit amet enim. Etiam ullamcorper. 
    Suspendisse a pellentesque dui, non felis. Maecenas malesuada elit 
    lectus felis, malesuada ultricies. Curabitur et ligula. Ut molestie a, 
    ultricies porta urna. Vestibulum commodo volutpat a, convallis ac, 
    laoreet enim. Phasellus fermentum in, dolor. Pellentesque facilisis. 
    Nulla imperdiet sit amet magna. Vestibulum dapibus, mau" 

var allText = ""; 

function putText() 
{ 
    document.getElementById("screen").innerHTML = allText; 
}; 

function writeText() 
{ 
    for(i=0; i<text.length; i++){ 
    allText = allText + text[i]; 
    setTimeout(putText, 150); 
}; 
} 

window.onclick = writeText; 
+0

这些可能对您有用-http:值,https://stackoverflow.com/questions/3462054/javascript-update-label-content-while-typing-inside-of-a-parent-input-with-jque –

+0

递归可能是最安全的解决方案,因为如果字符串非常长,浏览器不会一次性加载队列中的一些定时器。一次只有一个计时器。 – 4castle

回答

2

setTimout() function把函数从它的第一个参数上的队列以后运行,它不会中止当前函数的执行。因此,在从第一个setTimeout()调用putText()之前,您的整个for循环已完成,然后allText包含整个字符串。

此外,通过在循环中指定150的延迟,您将排队所有函数,从现在起运行150ms,而不是150ms。使用150 * (i+1)乘以循环计数器的延迟。

解决此问题的一种方法是使用setTimeout()可让您指定传递给您的函数的参数。因此,修改putText()接受要显示的文本参数,然后通过该值通过如下:

var text = 'Lorem ipsum dolor sit amet enim. Etiam ullamcorper.'; 
 

 
var allText = ""; 
 

 
function putText(text) { 
 
    document.getElementById("screen").innerHTML = text; 
 
} 
 

 
function writeText() { 
 
    for(i=0; i<text.length; i++){ 
 
    allText = allText + text[i]; 
 
    setTimeout(putText, 150 * (i+1), allText); 
 
    }; 
 
} 
 

 
window.onclick = writeText;
<div id="screen">Click here to start typing.</div>

我应该使用递归或可能制造类似的“休眠“功能?

你应该从未创建在试图暂停当前块的执行的功能意义上的“休眠”功能,因为那也是冻结整个浏览器。

可以实现使用一种伪递归与调用setTimeout()的延迟后再次运行本身的功能,也许有点像这样的打字:

function writeText(text) { 
 
    var currentLetter = 1; 
 
    function nextLetter() { 
 
    document.getElementById("screen").innerHTML = text.slice(0, currentLetter); 
 
    if (++currentLetter <= text.length) 
 
     setTimeout(nextLetter, 150); 
 
    } 
 
    nextLetter(); 
 
} 
 

 
var text = 'Lorem ipsum dolor sit amet enim. Etiam ullamcorper.'; 
 

 
window.onclick = function() { writeText(text); };
<div id="screen">Click here to start typing.</div>

0

你可以做这种递归,只是手动递增我而不是依靠for循环:

function writeText() { 
    if (i < text.length) { 
    setTimeout(writeText, 150); 
    allText += text[i]; 
    document.getElementById("screen").innerHTML = allText; 
    i++; 
    } 
} 

示例:https://codepen.io/petegivens/pen/VMxmXJ