What would I need to add to the code below to have the random redirect timeout for 5 seconds before triggering?

<script type="text/javascript">
(function(n){
 var pages = ['', '', ''];
 n = n < 3? 0 : n < 8? 1 : 2;
 window.location.replace(pages[n]);
})(Math.floor(Math.random() * 10));
</script>

I know what a regular redirect looks like, but I don't know where to place it within this special array.

<script type="text/JavaScript">
<!--
setTimeout("location.href = 'http://www.yourURL.com';",1500);
-->
</script>

Thanks for any help you're able to provide!

Member #949455 commented: Why you double post? +0

Dani AI

Generated

A few clarifications and a concise example to finish what started (and to answer ): the redirect itself should be delayed, not the array. Store plain URL strings (not HTML anchor markup), pick the index you want, then call the navigation inside a timer. Using location.replace avoids adding the current page to session history; location.href (or location.assign) preserves it.

<script>
(function(){
  var urls = [
    "https://example.com/one",
    "https://example.com/two",
    "https://example.com/three"
  ];

  // keep the original weighted selection if desired
  var r = Math.floor(Math.random() * 10);
  var i = (r < 3) ? 0 : (r < 8) ? 1 : 2;

  // delay 5000 ms (5 seconds) then navigate
  var timer = setTimeout(function(){
    window.location.replace(urls[i]);
  }, 5000);

  // optional: cancel redirect on user interaction
  document.addEventListener("click", function(){ clearTimeout(timer); }, { once: true });
})();
</script>

Troubleshooting notes: ensure the script runs at a sensible time (if showing a countdown or message, run after DOMContentLoaded). If users should be able to go back, use window.location.href = urls[i] instead of replace. For non-JS visitors, include a visible link or a <noscript> fallback so navigation remains accessible.

Recommended Answers

All 2 Replies

Member Avatar for Member #949455

Thanks for any help you're able to provide!

Isn't there someone who already help you with this?

No. No one helped.

I wasn't helped with the first, but found some extra info in the meantime. I was going to merely edit the first instead, but thought the lack of response was due to my lack of donation. So I opted to post again in order to donate to this great site. If no one knows the answer, it's ok. I've received more than my share of help from all of you. Thanks.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.