Change between two occurrences periodically

I am trying to rotate between 2 different .js files in my website. Here is the code I have:

<script type="text/javascript">
<!--
var jsfiles = ['/js/green.js', '/js/blue.js'];

var randomLink = Math.floor(Math.random() * jsfiles.length);

document.getElementById('scriptid').src = jsfiles[randomLink];
//-->
</script>
<script src="" id="scriptid"></script>

Is there a way to ensure that green.js loads 98% of the time, and blue.js only 2% of the time?

Answer №1

Would a simple solution like this work well for you? It ensures a consistent 98%/2% split each time.

const files = ['/js/red.js', '/js/yellow.js'],
    secondFileCount = 0,
    count = 0,
    randomizedFiles = [],
    randomNumber;

while (count < 100) {
    randomNumber = Math.floor(Math.random() * 2);

    if (randomNumber !== 1 || secondFileCount++ <= 2)
        count = randomizedFiles.push(files[randomNumber]);
}

console.log(randomizedFiles);

DEMO

Answer №2

If you're aiming for something that appears to be around 98%, regardless of the actual accuracy, you can attempt the following code:

var jsfiles = ['/js/green.js', '/js/blue.js'];

var randumNum = Math.floor(Math.random() * 100);

if(randomNum > 90)
    document.getElementById('scriptid').src = '/js/blue.js';
 else
    document.getElementById('scriptid').src = '/js/green.js';

This approach may not provide a precise 98% result due to the nature of randomness in JavaScript, but it could suffice if you only need one of two files and exact percentage isn't critical.

I've used > 90 instead of 98 because I believe this should give a result close to 99%, though randomization behavior in JS isn't guaranteed. It's up to you to decide how accurate you need it to be.

Answer №3

What do you think of this code?

if ((~~(Math.random()*100))<=95) alert('You're in the 95 zone'); else alert('Welcome to the 5 zone')

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Troubleshooting: ReactJS- Bootstrap Value Issue Not Displaying When Changing Tabs

I am currently working on a React App and utilizing react-bootstrap for development. However, I am encountering an issue where the content is only displaying correctly on the default nav item upon page refresh. When I switch to another nav item, the cont ...

Is there a way for me to identify what deletes CSS classes from an element during the first page load?

On a page where an element (specifically, a TextBox) initially has two CSS classes assigned when it loads, something strange is happening. After the page renders and JavaScript runs, the class attribute of the input element mysteriously becomes empty. I c ...

What is the process for configuring the Sequelize Postgres model type to inet in a database?

I have been utilizing the sequelize ORM to manage my postgress database. Within my postgress database, we have been using the inet data type to store IPv4 and IPv6 values. While creating models in sequelize, I encountered the issue of not finding the ine ...

Using an array as the source for your Mui Autocomplete instead of JSON

I'm attempting to recreate the autocomplete MUI example shown here, but with a slight variation. Instead of utilizing a JSON data structure, I am simply passing an Array. Here is what I have tried: export default function SearchTutorialArray() { con ...

Creating interactive navigation bar effects with scroll and click functionality using jQuery

Is there a way to make the navigation highlight when a user clicks on it and also scrolls to the corresponding section? Currently, I am facing an issue where only the third navigation event highlights, most likely because when navigating to the fourth or f ...

To ensure that quotes are correctly handled in a string being passed to a JavaScript function within an `onclick`

I am facing an issue with a cycle in a jspx file that I have. The cycle looks like this: <c:forEach var="var" items="${dataFile.list.rows}"> <li> <div> <a href="#" onClick="myFunct('${var.url}','escape(${var ...

An error occurred while attempting to execute the 'load' method on tabs that have not been initialized yet

Trying to use jquery-ui .tabs methods to refresh/load bootstrap tabs. $('#myTab a').on('click', function () { console.log("testing"); $("#myTab").tabs('load') }) Encountering this error message: Cannot ...

Create a new JavaScript object called "tree" with nested objects at any depth

My goal is to initialize a JavaScript object with empty objects containing a single key. For instance: getObject('one.two.three') Should create the object: {one:{two:{three:''}}} It seems that initializing with dynamic key names is ...

Steps for displaying an HTML table in Excel by clicking on a button

My goal is to open an HTML table in XLS format with a single click of a button. Currently, I have a JavaScript function that allows me to export the HTML table to XLS using the "save as" option. However, I want to enhance this functionality so that clickin ...

java code unicode feature in csharp

Here's the code I am using: $(document).ready(function () { var breadCrumps = $('.breadcrumb'); breadCrumps.find('span').text("<%= ArticleSectionData.title %>"); }); The 'title' property contains values en ...

Disappearing Act: How to Use Bootstrap Navbar to Hide Menu Items

Looking for a way to rearrange the elements in a standard bootstrap menu into the stack button when the screen size changes. <nav class="navbar navbar-expand-md navbar-dark bg-dark mb-4"> <a class="navbar-brand" href="#">Top navbar</a&g ...

Using Symbol.iterator in Typescript: A step-by-step guide

I have decided to upgrade my old React JavaScript app to React Typescript. While trying to reuse some code that worked perfectly fine in the old app, I encountered errors in TS - this is also my first time using TS. The data type I am exporting is as foll ...

Using the Trigger Method in a Vue JS Component with Sibling Components

Seeking assistance once again for a VueJS2 project. Currently, I have a setup with a parent component, along with child1 and child2. The scenario is that the form in child1 needs to receive data from child2, which acts as a table. When a checkbox on a row ...

Can you explain the distinction between Vue's 'v-on' directive and vue.$on method?

If I have two sibling components set up like this: <div id="root2"> <some-component>First</some-component> <some-component>Second</some-component> </div> ... and these components are coded as follows: Vue.comp ...

The $scope within the $ionicplatform is not functioning as expected

I've been working on an application, but it doesn't seem to be functioning correctly. Typically, when we add a value to the scope, I expect it to update in the application. Here is the snippet from index.html: <body ng-app="starter"> <i ...

Is it a bad idea to filter a large JSON object of about 6MB in AngularJS?

I am currently working on developing a barcode scanner application. The client has provided me with a 6mb CSV file containing data for various products. One approach I am considering is parsing the CSV file into a JSON object, extracting barcodes, and the ...

Troubleshooting problems with dataTransfer and the file input type in JavaScript

Working on a project, I'm currently exploring the idea of implementing a JavaScript drag-and-drop feature. Typically, when using drag and drop, one would pass the event.dataTransfer.files to an ajax call for uploading the file to an external PHP file ...

Switch the Ionic Slide Box to the "does-continue" setting

Currently in the process of constructing a slide-box containing numerous items. I've borrowed the code from the example provided here for an infinite number of items, and it's performing well. However, I have a considerable yet finite amount of ...

Exploring jQuery: Moving between different table cells using traversal techniques

Seeking assistance from experienced jQuery users as I am new to this library and may not be approaching this task correctly. I have a dynamically generated HTML table that is quite extensive. To enhance user experience, I aim to assign navigation function ...

Tips for making immutable state changes in React

Is there a way to update specific content in the state without affecting all other data stored in the state? Just to provide some context: The function below is executed within another "handleChange" function that takes the event as input and assigns the ...