I have this for inside my script:
for(var i = 0, l = eachLine.length; i < l; i++) {
if(eachLine[i].length>0){
doP(eachLine[i], +i);
}
}
the for read lines from a string and call doP function. What happens is it is too fast and cause some speed trouble in my webside depending on text size.
What I want is to call doP function every 10 seconds... in other words, I want for to wait 10 seconds to call doP function again... how can I make it work?
The setInterval() method calls a function at specified intervals (in milliseconds). The setInterval() method continues calling the function until clearInterval() is called, or the window is closed. 1 second = 1000 milliseconds.
The setInterval() method in JavaScript can be used to perform periodic evaluation of expression or call a JavaScript function.
Use the setInterval() method to call a function every N seconds in TypeScript, e.g. setInterval(myFunction, seconds * 1000) . The first parameter the method takes is the function that will be called on a timer, and the second parameter is the delay in milliseconds. Copied!
Use setInterval() to run a piece of code every x milliseconds. You can wrap the code you want to run every second in a function called runFunction .
Using setInterval()
var i = 0, len = eachLine.length;
function looper(){
if(i == 0)
interval = setInterval(looper, 10000)
if(eachLine[i].length > 0)
doP(eachLine[i], ++i);
if(i >= len)
clearInterval(interval);
}
looper();
var eachLine = ["Hi", "there", "I", "am", "lines", "of", "text"];
var i = 0, len = eachLine.length;
function looper(){
if(i == 0)
interval = setInterval(looper, 2000)
if(eachLine[i].length > 0)
doP(eachLine[i], ++i);
if(i >= len)
clearInterval(interval);
}
looper();
function doP(line, count){
$('body').append(count + ": " + line + "<br/>");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
Using setTimeout()
var i = 0, len = eachLine.length;
function looper(){
if(eachLine[i].length > 0)
doP(eachLine[i], ++i);
if(i < len)
setTimeout(looper, 10000);
}
looper();
var eachLine = ["Hi", "there", "I", "am", "lines", "of", "text"];
var i = 0, len = eachLine.length;
function looper(){
if(eachLine[i].length > 0)
doP(eachLine[i], ++i);
if(i < len)
setTimeout(looper, 2000);
}
looper();
function doP(line, count){
$('body').append(count + ": " + line + "<br/>");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With