Reputation: 21
Is it possible to create a truly random number in JavaScript?
I have tried here jsfiddle
Javascript:
// Mouse coordinates on click
var mouseX;
var mouseY;
$(document).ready(function(){
$("#btn1").click(function(e){
mouseX = e.clientX;
mouseY = e.clientY;
});
});
// Timing mouse down
var pressed;
var duration;
$(document).ready(function(){
$("#btn1").on("mousedown", function(){
pressed = +new Date();
});
$("#btn1").on("mouseup", function(){
duration = +new Date() - pressed;
});
});
// Time since last click
var loaded;
var onPush;
$(document).ready(function(){
loaded = +new Date();
$("#btn1").on("mousedown", function(){
onPush = +new Date() - loaded;
loaded = +new Date();
});
});
// Extending process for pseudorandom number? or creating a truly random number?
$(document).ready(function(){
$("#btn1").on("click", function(){
function rnum(min, max) {
var a = Math.random();
var ranMouseX = mouseX * a;
var ranMouseY = mouseY * a;
var ranDuration = duration * a;
var ranOnPush = onPush * a;
var combine = ((ranMouseX / ranOnPush) + (ranMouseY / ranDuration) % a);
$("#p1").text(((combine - Math.floor(combine)) * (max-min) + min).toFixed(0))
};
var f = document.getElementById('min');
var g = document.getElementById('max');
rnum(parseInt(f.value), parseInt(g.value));
});
});
But have I just extended the process for a pseudo-random number? or does this make a truly random number?
If it is still just a pseudo-random number how can I make a truly random number in JavaScript?
Upvotes: 1
Views: 3878
Reputation: 624
There is an API - ANU Quantum Random Number Generator API that you can use. From the description:
The numbers are considered to be "truly random", because they are generated by measuring the quantum fluctuations of a vacuum
Upvotes: 1
Reputation: 137171
From default APIs, you'll be stuck with pseudo-random (truly random would require a physical interface).
However, the Crypto
interface does provide a crypto-safe random number generator : Crypto.getRandomValues()
which seeds have more entropy than the default Math.random()
method.
var array = new Uint32Array(10);
window.crypto.getRandomValues(array);
for (var i = 0; i < array.length; i++) {
console.log(array[i]);
}
Upvotes: 3