skip to Main Content

Javascript
How to call a particular function (it contains img source from internet) 5 times and execute at same time …I uses randomuser api and let’s say I call the function 5 times but it takes 2 seconds to print the name and details of that random user! I want to call that function 5 times at that same time and display the values at that same time ..

Images
Image 1 :
Fetching api and please don’t mind about that userPic variable (i forget to change), it actually returns a Json results

Image 2
Actual code , and this is the function that i need fo call 5 times

I tried calling function 5 times but it seems maybe my lap was lag or actually my code was wrong or is there any other way

2

Answers


  1. In Javascript you can register Service Workers, like

    if (navigator.serviceWorker) { 
      // Start registration process on every page load 
      window.addEventListener('load', () => { 
          navigator.serviceWorker 
              // The register function takes as argument 
              // the file path to the worker's file 
              .register('/service_worker.js') 
              // Gives us registration object 
              .then(reg => console.log('Service Worker Registered')) 
              .catch(swErr => console.log( 
                    `Service Worker Installation Error: ${swErr}}`)); 
        }); 
    } 
    

    activate them, like

    
    // Call Activate Event 
    self.addEventListener('activate', e => { 
        console.log('Service Worker: Activated'); 
        // Clean up old caches by looping through all of the 
        // caches and deleting any old caches or caches that 
        // are not defined in the list 
        e.waitUntil( 
            caches.keys().then(cacheNames => { 
                return Promise.all( 
                    cacheNames.map( 
                        cache => { 
                            if (cache !== cacheName) { 
                                console.log('Service Worker: Clearing Old Cache'); 
                                return caches.delete(cache); 
                            } 
                        } 
                    ) 
                ) 
            }) 
        ); 
    }) 
    

    and you can also fetch

    
    
    var cacheName = 'geeks-cache-v1'; 
      
    // Call Fetch Event  
    self.addEventListener('fetch', e => { 
        console.log('Service Worker: Fetching'); 
        e.respondWith( 
            fetch(e.request) 
            .then(res => { 
                // The response is a stream and in order the browser  
                // to consume the response and in the same time the  
                // cache consuming the response it needs to be  
                // cloned in order to have two streams. 
                const resClone = res.clone(); 
                // Open cache 
                caches.open(cacheName) 
                    .then(cache => { 
                        // Add response to cache 
                        cache.put(e.request, resClone); 
                    }); 
                return res; 
            }).catch( 
                err => caches.match(e.request) 
                .then(res => res) 
            ) 
        ); 
    }); 
    

    (courtesy to geeksforgeeks for the scripts) and you can define your own file, register and activate them and then you can parallelize the work to be done. So, you can separate your function to be called into a separate file, register, activate and fetch it five times.

    Login or Signup to reply.
  2. There is no need for web workers. You can send your fetch calls one after the other and they will be processed in parallel. Once all of the promises have been resolved (Promise.all(...)) their collated results array will be processed.

    Your function ProfilePicSuggestion() could be the reason for your slow performance: it causes the DOM to be manipulated several times over. The resulting HTML will be invalid, as some of the id attributes will contain identical values. I have written an alternative function (pps()) that will return an HTML string for each suggestion. The individual HTML strings will be .join("n")-ed and assigned to the .innerHTML attribute of the #suggestion-users-container-div.

    function shfl(a){ // Durstenfeld shuffle for creating a random array sequence:
     for(let j,i=a.length;i>1;){
      j=Math.floor(Math.random()*i--);
      if (i!=j) [a[i],a[j]]=[a[j],a[i]]
     }
     return a
    }
    
    function pps([img,nam]){
     return `<div><img src="${img}"><p>${nam}</p><button>follow</button></div>`;
    }
    
    const url="https://dummyjson.com/users/",
      arr=shfl(Array(208).fill(0).map((_,i)=>i+1));
    
    async function getData(id){
     return fetch(url+id).then(r=>r.json()).then(d=>[d.image,d.firstName+" "+d.lastName]);
    }
    
    Promise.all(arr.slice(0,10).map(getData)).then(data=>document.getElementById("suggestion-users-container").innerHTML=data.map(pps).join("n"));
    #suggestion-users-container>div{margin:6px;border:1px solid grey}
    <div id="suggestion-users-container"></div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search