Header menu


Saturday, 1 March 2014

Iteration through array with delay in jquery

What my problem is I have an array and i have to pass array element to some function with some delay between each call. Now if i iterate using loop the iteration has already been completed before calling function and i am only able to pass last value of my array to function. To deal with this i found a way using recursion such that there is delay between my each call to function.

Now in my example :
l is length of array
arr is array
k is index
tex is my function i am calling


 var k=0;
 var arr=[1,2,3,4,5,6,7,8];
 function tex(arr,k,l){

                                 setTimeout(function() { k++; tex(arr,k,l); },3000);

This is basic structure of code and it will call tex() after each 3 sec and tex will alert array elements one by one.

To understand more run below example:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
<script type="text/javascript" >
            var k=0;;
            var arr=[1,2,3,4,5,6,7,8];
            function tex(arr,k,l){
                                $( "#1" ).append("Iteration "+arr[k]+" ... ");
<div id="1">This is my Iteration test...</div>