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
In Javascript you can register Service Workers, like
activate them, like
and you can also fetch
(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.
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 theid
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.