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

Example:


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

                                 alert(arr[k]);
                                 setTimeout(function() { k++; tex(arr,k,l); },3000);
                               }
                }
  tex(arr,k,8);    


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:

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

No comments:

Post a Comment