Erite javascript script to send http get requests in a loop
- User
Erite javascript script to send http get requests in a loop
- Assistant
Sure, here's a JavaScript script to send HTTP GET requests in a loop:
async function sendRequest(url) { const response = await fetch(url); const data = await response.json(); console.log(data); } function sendGetRequestsInLoop(url, interval, times) { let counter = 0; const timer = setInterval(() => { sendRequest(url); counter++; if (counter === times) { clearInterval(timer); } }, interval); } // Usage Example: Send 5 requests every 2 seconds. const apiUrl = 'https://api.example.com/data'; const requestInterval = 2000; // in milliseconds const requestTimes = 5; sendGetRequestsInLoop(apiUrl, requestInterval, requestTimes);In the above script, the
sendRequestfunction is using thefetchAPI to send an HTTP GET request to the specifiedurl. It then logs the received JSON data to the console.The
sendGetRequestsInLoopfunction takes in theurl,interval, andtimesparameters. It sets up an interval timer that calls the function at a specified (in milliseconds). The loop will run for number of iterations before stopping.