I'm working with percentage and the setInterval()
so I have a
var intervalId;
function randomize(){
var prc = $("#prc").val();
var c = 0 ;
if (!intervalId){
intervalId = setInterval(function(){
c = c + 1;
var attempt = Math.random() * 100;
if (attempt <= prc){
clearInterval(intervalId);
intervalId = false;
$("#attemptnbr").val(c);
}
}, 100);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
Percentage : <input type="text" id="prc"/>
<button onclick="randomize()">GO</button>
Number of attempts :<input type="text" id="attemptnbr"/>
But actually if the user set the #prc
input to 50.345.34
, the attempt <= prc
condition always returns true
.
I tried to console.log(isNaN(prc))
when this input is set to a number like 50.345.34
and it always returns false
.
Why is it considered as a numeric value?
But actually if the user set the #prc input to 50.345.34, the attempt <= prc condition always returns true.
Pretty sure that's observation error. Your prc
is a string, which will then be implicitly converted to a number by the <=
operator. The number will be NaN
because "50.345.34" can't be implicitly converted, and relations using NaN
are never true.
However it doesn't really change what you want to do about it, which is convert prc
to a number on purpose and test the result:
var intervalId;
function randomize(){
var prc = +$("#prc").val();
// ^------------------- Note the +, that converts it to a number
if (isNaN(prc)) {
// Handle the invalid input
return;
}
var c = 0 ;
if (!intervalId){
intervalId = setInterval(function(){
c = c + 1;
var attempt = Math.random() * 100;
if (attempt <= prc){
clearInterval(intervalId);
intervalId = false;
console.log(attempt);
}
}, 100);
}
}
I should note that the above may do something you don't want if the input is empty: It will use the value 0
, because +""
is 0
. If you don't want that, you might do this:
var prcString = $.trim($("#prc").val());
var prc = +prcString;
if (!prcString) {
// Handle the fact they didn't enter anything
return;
}
if (isNaN(prc)) {
// Handle the invalid input
return;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With