2017-10-10 53 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