Reputation: 32331
I have an array of symbols in javascript .
For each element of an Array , i am sending it to a server , and i am doing this operation continously for every 10
seconds using setTimeout .
My requirement is that , once i process the half of the symbols in the array , i want to give a pause the operation for 3 seconds .
(The size of the array is fixed that is 100 , so i can directly use the condition if it reached 50 )
I have tried this with a sample program ,
I observed that when the page is loaded for the first time , affter reaching 2 symbols , its ausing for 2 seconds . and from the next iteartion its not pauisng .
Could anybody please help me
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript">
var symbols = ["One","Two","Three","FOur"];
var i = 0;
function doPoll() {
$.each( symbols, function( index, value ){
loadXMLDoc(value);
});
setTimeout(doPoll, 10000);
}
$(document).ready(function () {
doPoll();
});
function loadXMLDoc(value)
{
i++;
alert(value);
if(i==2)
sleep(1000);
}
function sleep(milliseconds) {
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > milliseconds){
break;
}
}
}
</script>
</head>
<body>
</body>
</html>
Upvotes: 0
Views: 231
Reputation: 816790
In your case you can simply iterate over the first half of the array (with a normal for
loop), use setTimeout
and then iterate over the second half of the array:
function doPoll() {
var middle = Math.round(symbols.length / 2);
for (var i = 0, l = middle; i < l; i++) {
loadXMLDoc(symbols[i]);
}
setTimeout(function() {
for (var i = middle, l = symbols.length; i < l; i++) {
loadXMLDoc(symbols[i]);
}
setTimeout(doPoll, 10000);
}, 2000);
}
See also: Best way to insert a 'pause' in a .each enumeration
Upvotes: 1