0

I'll try explain it further, I'm building a web-art website and there is a page that is supposed to have rare chance to redirect to a different page.

After 10 seconds, the page redirects to two possible pages, one being rarer than the other basically

Just one page that has a chance to redirect to two different possible pages.

I have the code down for it to redirect to the common page after 10 secs:

<script> var timer = setTimeout(function() { window.location='/error.html' }, 10000); </script>
bitsnake
  • 15
  • 2
  • Possible duplicate of [How to redirect to another webpage in JavaScript/jQuery?](https://stackoverflow.com/questions/503093/how-to-redirect-to-another-webpage-in-javascript-jquery) – Tyzoid Aug 13 '17 at 20:21
  • 2
    Something like this: `var rareChance = 0.01; if (Math.random() – Alex Kudryashev Aug 13 '17 at 20:24

1 Answers1

0

This script will wait 10 seconds and redirect to a random page, rare.html or normal.html. The rare.html page will get hit 15% of the time, normal.html will get hit 85% of the time.

<script>
var WAIT_MS = 10000; // 10 seconds
var PERCENT = 0.15;  // 15% chance
setTimeout(function() {
    if (Math.random() <= PERCENT) {
        window.location = 'rare.html'
    } else {
        window.location = 'normal.html'
    }
}, WAIT_MS);
</script>

We can prove this works by running the Math.random() function 100 times and we should see about 15 results less than 0.15.

var PERCENT = 0.15;
var rareCount = 0;
var normalCount = 0;

for (var i = 0; i < 100; i++) {
    if (Math.random() <= PERCENT) {
        rareCount++;
    } else {
        normalCount++;
    }
}
console.log(rareCount, ' rare');
console.log(normalCount, ' normal');
styfle
  • 22,361
  • 27
  • 86
  • 128