I want to create number generator but i want to control it better so i want to first generate number 30 and every next number should be in the range from 1 to 1000. I have done it but the last part dont work, it every time show 30. Can you help me? Thanks! (The code is ready to edit so there is everything good i just need some advice how to edit code to shnow second and every next number in range from 1 to 1000! THANKS!
var button = document.querySelector("button");
var number = document.querySelector("#number");
const nRuns = 12;
const timeout = 100;
let iterator = 0;
button.addEventListener( "click", textC);
function textC(){
number.textContent = `${Math.floor(Math.random() * 1000) + 1}\n`;
iterator += 1;
if (iterator < nRuns) {
setTimeout(textC, timeout)
} else{
iterator = 0;
number.textContent = 30;
}
}
<p id="number"></p>
<button>Generate</button>
this should work.
var button = document.querySelector("button");
var number = document.querySelector("#number");
const nRuns = 12;
const timeout = 100;
let iterator = 0;
let random = false;
button.addEventListener( "click", textC);
function textC(){
let n = Math.floor(Math.random() * 1000) + 1;
number.textContent = `${n}\n`;
iterator += 1;
if (iterator < nRuns) {
setTimeout(textC, timeout)
} else{
iterator = 0;
number.textContent = random ? n : 30;
random = true;
}
}
<p id="number"></p>
<button>Generate</button>
You need to switch the start and end values.
var button = document.querySelector("button");
var number = document.querySelector("#number");
const nRuns = 12;
const timeout = 100;
let iterator = 0;
button.addEventListener( "click", textC);
function textC(){
number.textContent = iterator === 0
? 30
: Math.floor(Math.random() * 1000) + 1;
iterator++;
if (iterator < nRuns) {
setTimeout(textC, timeout);
} else {
iterator = 0;
}
}
<p id="number"></p>
<button>Generate</button>
Related
something like this but for alphabets:
<p id="result"></p> <!-- this is code for random num gen ,I need something like this for alphabet.-->
<script>
var intrvl = setInterval(numbFunction, 500); //repeat function after 1.5 seconds(1500 ms)
function numbFunction() {
var x = Math.floor(Math.random() * 10 + 1); //return a random no. between 1 to 10
document.getElementById("result").innerHTML = x;
}
</script>
setInterval(function(){
document.getElementById('result').innerHTML = String.fromCharCode(Math.floor(Math.random() * 25) + 97);
}, 500);
Taking advantage of the character code ordering
var intrvl = setInterval(numbFunction, 500);
function numbFunction() {
var characters = 'abcdefghijklmnopqrstuvwxyz';
var charactersLength = characters.length;
var x = Math.floor(Math.random() * charactersLength + 1);
document.getElementById("result").innerHTML = characters[x]
}
<p id="result"></p>
setInterval(randomGen, 500);
function randomGen() {
const alphabet = "abcdefghijklmnopqrstuvwxyz"
const random = alphabet[Math.floor(Math.random() * alphabet.length)];
document.getElementById("rand").innerHTML = random;
}
<p id="rand"></p>
var player1 = Math.floor(Math.random() * 6) + 1;
const score = [];
const scorelength = 6;
function generate() {
if (score.length < scorelength) {
score.push(player1)
console.log(score);
}
If you declare player 1 score outside of the function you will end up with the same score 6 times
const scorelength = 6;
function generate() {
var player1 = Math.floor(Math.random() * 6) + 1;
if (score.length < scorelength) {
score.push(player1)
}
console.log(score);
}
generate();
Your question isn't clear but if you need to do something with your array each time a number is pushed inside, you can use a recustive function as follow :
<div id="app">
<button onclick="generate()">Generate</button>
</div>
<script>
var myArray = [];
function generate() {
if(myArray.length <= 10){
myArray.push(Math.floor(Math.random() * 100));
console.log('Do something, array = ', myArray);
generate();
}
}
</script>
I want to make the code bellow to calculate the time it takes to run the loop, but somehow none of the things I have tried worked!
I have tried using date, but it provides really inaccurate timing.
I have tried using another interval to check if an element already exists, and some similar solutions, etc, but the result is always the same, Javascript always checks things before the loop finishes!
var t = 0;
function myStartFunction() {
myVar = setInterval(function() {
t++;
document.getElementById("tempo").innerHTML = "Elapsed time: " + t + " segundos";
}, 1000);
}
myStartFunction();
function myStopFunction() {
clearInterval(myVar);
}
var n = "";
var i = 0;
while (i < 100000) {
n += "<br>" + i;
i++;
if (i == 100000) {
///////////////////clearInterval(myVar);
}
}
document.getElementById("range").innerHTML = n;
<!DOCTYPE html>
<html>
<body>
<h2 style="font-family:arial">TIME TO RUN LOOP</h2>
<hr> <br>
<button onclick="myStopFunction()">STOP</button> <br>
<p id="tempo" style='font-family:arial'>Elapsed time: 0 segundos</p>
<p id="range" style='font-family:arial'></p>
</body>
</html>
The best answer would be one that would provide an elapsed time in the following format: 00:00:00:0000
... without the need of a button!
And with a working clearInterval(myVar); where currently there is a Javascript comment.
use performance (see MDN). Or check this jsFiddle
let t = 0;
let start = performance.now();
let padZero = (v, n = 2) => `${v}`.padStart(n, "0");
let toTime = v =>
`elapsed (hh:mm:ss:ms) ${
padZero(Math.floor(v/(60*60000)))}:${
padZero(Math.floor(v/60000))}:${
padZero(Math.floor(v/1000))}:${
padZero(Math.floor(v%1000), 3)}`;
myStartFunction();
function myStartFunction() {
if (performance.now() > 10000) {
return console.log(`${toTime(performance.now() - start)} END`);
}
console.log(toTime(performance.now() - start));
setTimeout(myStartFunction, 1000);
}
.as-console-wrapper { top: 0; max-height: 100% !important; }
Updated: I made this in the correct format with KooiInc code and changed out Date.Time for performance.now().
I changed your code a bit, this should calculate the time correctly for your while loop. Comment out the rest of your JavaScript code and put this code in your script.
I don't understand what you need for the ClearIntervalFunction exactly, but I can help you create that function if you give me more details on what you need.
function loop() {
let n = "";
let i = 0;
while (i < 100000)
{
n += "<br>" + i;
i++;
}
return n;
}
function segundoFormatter(segundo) {
let zeros = 8;
let segundoArray = segundo.toString().split(".");
let number2Add = zeros - segundoArray[0].length;
let STR = "";
for(let i = 0; i < number2Add; i++){
STR += "0";
if(i == 1 || i == 3 || i == 5){
STR += ":";
}
}
let finalStr = STR + segundoArray[0] + segundoArray[1];
return finalStr.toString().substring(0,13);
}
window.onload = function(){
let startTime = performance.now()
let n = loop();
let endTime = performance.now()
let timeLoopTakes = (endTime - startTime);//00:00:00:0000
// segundoFormatter(timeLoopTakes);
document.getElementById("tempo").innerHTML = "Elapsed time: " +
segundoFormatter(timeLoopTakes) + " segundos";
//You can uncomment this line belowand get like 10000 things in your dom
//document.getElementById("range").innerHTML = n;
}
You can use the getTime() function of the Date object to get the UNIX timestamp associated with the current time.
let initialTime = new Date().getTime();
for(let i = 0; i < 100000000; i ++) {
// do something
}
let finalTime = new Date().getTime();
console.log ('this took : ' + (finalTime - initialTime) + ' milliseconds' );
I am using the below code to assign a random class (out of five) to each individual image on my page.
$(this).addClass('color-' + (Math.floor(Math.random() * 5) + 1));
It's working great but I want to make it so that there are never two of the same class in a row.
Even better would be if there were never two of the same in a row, and it also did not use any class more than once until all 5 had been used... As in, remove each used class from the array until all of them have been used, then start again, not allowing the last of the previous 5 and the first of the next 5 to be the same color.
Hope that makes sense, and thanks in advance for any help.
You need to create an array of the possible values and each time you retrieve a random index from the array to use one of the values, you remove it from the array.
Here's a general purpose random function that will not repeat until all values have been used. You can call this and then just add this index onto the end of your class name.
var uniqueRandoms = [];
var numRandoms = 5;
function makeUniqueRandom() {
// refill the array if needed
if (!uniqueRandoms.length) {
for (var i = 0; i < numRandoms; i++) {
uniqueRandoms.push(i);
}
}
var index = Math.floor(Math.random() * uniqueRandoms.length);
var val = uniqueRandoms[index];
// now remove that value from the array
uniqueRandoms.splice(index, 1);
return val;
}
Working demo: http://jsfiddle.net/jfriend00/H9bLH/
So, your code would just be this:
$(this).addClass('color-' + (makeUniqueRandom() + 1));
Here's an object oriented form that will allow more than one of these to be used in different places in your app:
// if only one argument is passed, it will assume that is the high
// limit and the low limit will be set to zero
// so you can use either r = new randomeGenerator(9);
// or r = new randomGenerator(0, 9);
function randomGenerator(low, high) {
if (arguments.length < 2) {
high = low;
low = 0;
}
this.low = low;
this.high = high;
this.reset();
}
randomGenerator.prototype = {
reset: function() {
this.remaining = [];
for (var i = this.low; i <= this.high; i++) {
this.remaining.push(i);
}
},
get: function() {
if (!this.remaining.length) {
this.reset();
}
var index = Math.floor(Math.random() * this.remaining.length);
var val = this.remaining[index];
this.remaining.splice(index, 1);
return val;
}
}
Sample Usage:
var r = new randomGenerator(1, 9);
var rand1 = r.get();
var rand2 = r.get();
Working demo: http://jsfiddle.net/jfriend00/q36Lk4hk/
You can do something like this using an array and the splice method:
var classes = ["color-1", "color-2", "color-3", "color-4", "color-5"];
for(i = 0;i < 5; i++){
var randomPosition = Math.floor(Math.random() * classes.length);
var selected = classes.splice(randomPosition,1);
console.log(selected);
alert(selected);
}
var used = [];
var range = [0, 5];
var generateColors = (function() {
var current;
for ( var i = range[0]; i < range[5]; i++ ) {
while ( used.indexOf(current = (Math.floor(Math.random() * 5) + 1)) != -1 ) ;
used.push(current);
$(" SELECTOR ").addClass('color-' + current);
}
});
Just to explain my comment to jfriend00's excellent answer, you can have a function that returns the members of a set in random order until all have been returned, then starts again, e.g.:
function RandomList(list) {
var original = list;
this.getOriginal = function() {
return original;
}
}
RandomList.prototype.getRandom = function() {
if (!(this.remainder && this.remainder.length)) {
this.remainder = this.getOriginal().slice();
}
return this.remainder.splice(Math.random() * this.remainder.length | 0,1);
}
var list = new RandomList([1,2,3]);
list.getRandom(); // returns a random member of list without repeating until all
// members have been returned.
If the list can be hard coded, you can keep the original in a closure, e.g.
var randomItem = (function() {
var original = [1,2,3];
var remainder;
return function() {
if (!(remainder && remainder.length)) {
remainder = original.slice();
}
return remainder.splice(Math.random() * remainder.length | 0, 1);
};
}());
I've got this project where I have to generate random mathematics sums...
They are all 'divide by' sums, so I want to make all numbers even.
Can anyone help me with this? just ask if I'm not clear enough =)
<script>
$(function() {
var number = document.getElementById("breuken"),
i = 1;
for (; i <= 10; i++) {
var sRandom = Math.floor(Math.random()*10 + 1),
fRandom = Math.floor(sRandom + Math.random()*(20-sRandom )),
calc = Math.abs(fRandom / sRandom),
textInput = document.createElement('input'),
span = document.createElement('span'),
p = document.createElement('p');
textInput._calc = calc;
textInput.onchange = (function(p) {
return function(ev) {
var self = ev.target;
if (self.value == self._calc) {
p.style.color = 'green';
};
};
})(p);
span.innerHTML = fRandom + " : " + sRandom + " = ";
p.appendChild(span);
p.appendChild(textInput);
number.appendChild(p);
};
});
</script>
To get an even random number just:
halve you range and multiply by 2
var range = 100;
var number = Math.floor( Math.random() * range / 2 ) * 2;
or keep getting random numbers until you get an even one
var number;
do {
number = Math.floor(Math.random()*10 + 1)
} while( number % 2 == 1 );
Get a random integer over 1/2 the range and double it.