What is the most efficient way to generate a single random value?

Is there a way to generate a random value only once and ensure that it remains constant, even when called within a function? If I use the Random method inside a function, the value of 'x' changes every time the function is called due to the method generating a new value each time.

I tried creating a global variable and assigning the result of the Random method to it. This worked in ensuring the random value remained the same. However, I need the range of the random value to be defined based on user input. Since user input needs to come before the Random method runs, this approach doesn't work.

So, what should be done in this scenario? The user should be able to define the range of the random value, while 'x' should only take on a single value.

This is important because I plan to use the 'x' variable in another method.

    
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "w3.org/TR/html4/strict.dtd">
<html>
<head>
    <title>Test</title>
    <link rel="stylesheet" href="jscss.css" />
</head>
<script>var size = document.getElementById("size"); var x = Math.floor(Math.random(size) * (5)) + 1; function afunc() { alert(x); }</script>
<body>
    <input type="number" id="size"><br /> <button onclick="afunc()">Submit</button><br />
</body>
</html>

Answer №1

var x;
function changeSize(){
  var size = document.getElementById("size").value; 
  x = Math.floor(Math.random(size) * (5)) + 1; 
  console.log("size:",size,"X:",x);
}
function afunc() { alert(x); }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js></script>";

<input type="number" id="size" onchange="changeSize();"><br />; 
<button onclick="afunc()">Submit</button><br />

Edit: for variable x load only one time

var x;
function changeSize(){
  var size = document.getElementById("size").value; 
  if(!x){
    x = Math.floor(Math.random(size) * (5)) + 1; 
  }
  console.log("size:",size,"X:",x);
}
function afunc() { alert(x); }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js></script>";

<input type="number" id="size" onchange="changeSize();"><br />;
<button onclick="afunc()">Submit</button><br />

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

Utilize React HOC (Higher Order Component) and Redux to retrieve data and pass it as props

In my quest to develop a Higher Order Component (HOC) that can execute methods to fetch data from the backend and display a loader mask during loading, I encountered a challenge. I aim to have the flexibility of passing different actions for various compon ...

There seems to be an issue with the DownloadDir functionality of the node-s3-client library, as

I am currently using a node s3 client library called 'node-s3-client' for syncing directories between S3 and my local server. As per the guidelines provided in the documentation, here is the code I have implemented: var s3 = require('s ...

What steps should I take to generate a 2-Dimension Input Array from scratch?

I am working on a project that involves creating a 2-Dimensional array of text-based numerical inputs. I aim to use the standard HTML input type box for this purpose: <input type="text"> The number of rows and columns in the array will depend o ...

Leveraging Selenium for testing Polymer components and shadow DOM structures

Having trouble using Selenium with elements inside a shadow DOM. Is there a specific method to handle this situation? Any guidance on what I might be doing wrong? Here are the various approaches I've attempted: var webdriver = require('selenium ...

Tips for utilizing the two-function in jQuery to showcase one DIV following another DIVNote: When using the two-function

Apologies in advance for my poor English skills, but I have been contemplating whether to write here and if you will be able to understand me. I am currently working on a jQuery script: $(function() { $('#div1').hover(function() { $ ...

Restart the AJAX form submission process to enable the sending of updated information

Looking for a popup form to use on your website? The issue is that after the form is submitted once, it doesn't show again to send different information. The only solution seems to be reloading the page, but that's not ideal. Check out this tuto ...

How can I modify the mesh structure in Three.js?

Having two meshes, mesh1 and mesh2, each with the same number of vertices and extrusion. mesh1 = 5000 vertices. mesh2 = 5000 vertices. I transfer the vertices from mesh2 to mesh1. Then I execute: mesh2.geometry.verticesNeedUpdate = true; mesh2.geometry. ...

Finding image input loading

When working with the following code: <input type="image" ... onLoad="this.style.opacity = 1" /> Everything seemed to be functioning well in IE, but encountered an issue in Chrome where the onLoad event failed to trigger upon image load. It's ...

Ways to determine if a substring is contained within the text of an array item

Recently, I've been researching ways to check if a certain value exists in an array using indexOf('textvalue'). However, I have encountered the issue of my 'textvalue' being a substring, which causes no matches to be found. The pro ...

Utilizing factory service within a decorator in AngularJS

Utilizing the TextAngular plugin and attempting to customize a toolbar, I am striving to inject my own service (LinkService) into the module but encountering an [$injector:unpr] Unknown provider issue. module.config(function($provide, LinkService){ $p ...

How do you determine the dimensions of a background image?

My div is a perfect square, measuring 200 pixels by 200 pixels. The background image I've chosen to use is larger at 500 pixels by 500 pixels. I'm searching for a method to ensure that the entire background image fits neatly within the confines ...

Refashioned: The Bootstrap design shifter concept

Hi there! I am currently working on implementing a layout shifter pattern with Bootstrap 4. So far, I have successfully positioned 2 colored boxes responsively, but I am facing some challenges with getting the third box in the right place. If you have an ...

What is the best way to combine an array of objects into a single object in typescript?

Looking for some help with converting an array of objects into a single object using TypeScript. Here's the structure of the array: myArray = [ {itemOneKey: 'itemOneValue', itemTwoKey: 'itemTwoValue'}, {itemThreeKey: ' ...

Is there a way to retrieve the information from the v-text-field without using the v-model directive?

<div v-for="i in parseInt(questionCount)" :key="i"> <v-layout> <v-flex xs6 offset-3 mt-15" > <label for=""> Enter question number {{index}}:</label> <v-text-fi ...

How to automatically choose the first option in a v-for loop in Vue.js

I have a loop that creates a dropdown menu from an array: <select class="form-control" v-model="compare_version" > <option v-for="(version, index) in allVersions" v-bind:value="index" v-bind: ...

How can I show the remaining paragraph text upon clicking a button in a responsive manner using CSS and JavaScript?

I want to add a nice animation effect to the height of my text when a button is clicked. I've managed to achieve this by setting a height: 30px with overflow: hidden initially, and then toggling a class with height: 300px. However, I'm facing an ...

Guide on how to update a div element without losing submitted information with the help of AJAX and PHP

After creating two HTML pages that incorporate AJAX refresh div tag code and use $_POST to post data from one page to another, I encountered a situation where the PHP page would retrieve data from a MySQL table. Let's take a look at the code I utilize ...

HTML and CSS are two separate languages that work together to create web pages

I'm experiencing an issue with my CSS file not responding to my HTML file. I have imported the CSS file into my HTML file and both files are located in the same directory. It was working fine when they were written in the same file, but after separati ...

Display the homepage if a user accesses a page intended for an ajax request

Currently, I am utilizing jQuery to create a straightforward website. The main page is called 'index.html' and it has the capability to load different content (such as 'info1.html' or 'info2.html') through jQuery ajax requests ...

What other methods can be used to initiate an Ajax request?

I'm curious about the most efficient approach to making an AJAX call. My current code works perfectly fine: $.ajax({ url: "/rest/computer", type: "GET", dataType: "json", data: { assessmentId: "123", classroomId: " ...