簡體   English   中英

javascript函數延遲或設置超時不起作用

[英]javascript function delay or set time out not working

我試圖在javascript中編碼類型化的jquery函數。我快要在那里了。在這里我需要在加載單詞后添加一個延遲。每個單詞加載后需要幾個secons(至少要說4秒)。 我該怎么做。 嘗試延遲並設置超時。它對我不起作用或我放置在錯誤的位置。 我該如何設置。

 var count = 0, count2 = 0, arr = ["SWOO", "EXCITE", "WOW", "AMAZE", "IMPRESS", "EDUICATE"], dir = true; setInterval(function() { var interval = setInterval(function() { document.getElementById('p1').innerHTML = arr[count].substring(0, count2); if (dir) { count2++; if (count2 >= arr[count].length) { dir = false; } } else { count2--; if (count2 < 0) { dir = true; clearInterval(interval); } } }, 100); count++; if (count == 6) count = 0; }, 2500); 
 <div style="width=100%"> <span id="p1" className="p2 hero-text-animate"></span> <span>them with video</span> </div> 

如果在數組中添加“很長的字符串”,則實現會出現問題。 我已經修改了您的代碼,希望對您有所幫助。

 var count = 0, count2 = 0, arr = ["SWOO", "EXCITE", "WOW", "AMAZE", "IMPRESS", "EDUICATE"], dir = true; var p1 = document.getElementById("p1"); // Turning the intervals to on or off. var onOff = function(bool, func, time) { if (bool === true) { interval = setInterval(func, time); } else { clearInterval(interval); } }; var eraseCharacters = function() { // How long we want to wait before typing. var wait = 1000; // How fast we want to erase. var erasingSpeed = 100; var erase = function() { p1.innerHTML = arr[count].substring(0, count2); count2--; if (count2 < 0) { dir = true; // Stop erasing. onOff(false); count++; if (count === 6) { count = 0; } // Start typing. setTimeout(startTyping, wait); } }; // Start erasing. onOff(true, erase, erasingSpeed); }; var startTyping = function() { // How long we want to wait before erasing. var wait = 4000; // How fast we want to type. var typingSpeed = 100; var type = function() { p1.innerHTML = arr[count].substring(0, count2); if (dir) { count2++; if (count2 > arr[count].length) { dir = false; // Stop typing. onOff(false); // Start erasing. setTimeout(eraseCharacters, wait); } } }; // Start typing. onOff(true, type, typingSpeed); }; // Start typing after 2 seconds. setTimeout(startTyping, 2000); 
 <div style="width=100%"> <!-- Maybe it should be class. --> <span id="p1" className="p2 hero-text-animate"></span> <span>them with video</span> </div> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM