Creating delayed redirect with background API call and dynamic URL generation

I’m new to web development and need help with JavaScript functionality.

I want to build a page that does three things in sequence:

  1. Show a countdown timer (around 10 seconds) when someone visits
  2. While counting down, silently send a GET request to an external webhook service in the background
  3. After the timer ends, automatically redirect the visitor to a destination URL that includes data from the original request parameters

Basically I need to process some webhook automation while the user waits, then send them to a customized landing page. The final redirect location should be built using variables from the initial page URL.

What’s the best approach to handle this kind of timed workflow with background requests? I’m comfortable with basic HTML but JavaScript is still confusing for me.

for your needs, check out setInterval() instead, it helps keep track of the countdown better. Also, use fetch() for that API call. Don’t forget to stop the interval when the countdown ends, otherwise itll keep going. good luck!

Certainly, this task involves using JavaScript capabilities effectively. You can begin with the setTimeout() function to implement your countdown timer. Simultaneously, initiate the background API call using fetch(), ensuring the timer starts independently of the API response. To construct your redirect URL, utilize URLSearchParams to extract the necessary parameters from the current URL, which can then be appended to your desired base URL. It’s crucial to incorporate error handling for your API request to ensure the redirect still occurs even if the call fails. Additionally, consider what actions to take if the user navigates away before the countdown completes. The actual line for redirection is straightforward: window.location.href = yourDestinationURL. This process should work seamlessly across all modern browsers.

I’ve dealt with this before - there are some traps to watch out for. The timing gets tricky since your API call might finish before or after the countdown ends. I used Promise.all() to handle both the timer and fetch request, but always respected the minimum wait time no matter how fast the API responded. Heads up - some browsers throttle background requests on inactive tabs, so test this thoroughly. For building URLs, encode your parameters properly. I learned this the hard way when special characters broke my redirects. One more thing: add a fallback redirect URL if your API call fails completely. Otherwise users get stuck on the countdown page forever.

This topic was automatically closed 4 days after the last reply. New replies are no longer allowed.