While not Stopping on Condition - javascript

how are you?
I am facing some issues with my code running on a snippet.
First: I do not know why when I try to run it, the loop does not finish
Second: One of my friends paste the code and ran on his computer and the loop finish but after running the second time the variables are sum with the new values inserted.
We are all using Google Chrome. Can anyone help me? Thanks.
var i = 0;
var speed = parseInt(prompt('value 1'));
var long = parseInt(prompt('value 2'));
var vel2 = velocidad;
while (speed> 0){
i++;
if (i>speed){
speed--;
}
console.log(speed);
}
sub_i = (i * vel2) - vel2;
console.log('Total i ' + i);

all you need is to initialize i = 0

Related

Changing a for loop to a while loop, average of dice rolls

Can anyone help me write this function as a while loop instead of a for loop?
function RollAverage(){
//assumes: outputDiv is available for output
//results: counts rolls and averages them
var userNum,countTotal,rollSum;
userNum=parseFloat(document.getElementById('textBox').value);
countTotal=0;
for (rollSum=0; countTotal<userNum; countTotal=countTotal++){
rollSum=rollSum+(RandomInt(1,6) + RandomInt(1,6));
countTotal++;
}
document.getElementById('outputDiv').innerHTML='Heres the average ' +(rollSum/countTotal);
}
Are you using any specific library for RandomInt() ? I have used instead
Math.floor(Math.random(1,6) and modified the code for while loop as below:
function RollAverage(){
var userNum,countTotal,rollSum;
userNum=parseFloat(document.getElementById('textone').value);
countTotal=0;
rollSum=0;
while (countTotal < userNum){
rollSum = rollSum + (Math.floor(Math.random(1,6) + Math.random(1,6)));
countTotal++;
}
document.getElementById('myDivId').innerHTML =(rollSum/countTotal);
}
Full working jsfiddle code here

Infinte loop is killing my NodeJS server

As the title says, I think my server can't handle the speed of calculations of the infinite loop, how would I make it so the calculations still go very quick but the server doesn't crash? also when I try this in jsfiddle it eventually crashes my browser.
Here's the code:
<script>
function crashPoint(){
var currentTry = 2;
var mainMultplier = 1;
var secMultiplier = Math.random();
for(;;){
var randomInt = Math.floor(Math.random() * 100) + 1;
if(1/currentTry*100 < randomInt){
currentTry = currentTry+1;
mainMultplier = mainMultplier+1;
}else{
console.clear();
break;
}
}
var totalMultiplier = mainMultplier+secMultiplier;
if(totalMultiplier > 2){
totalMultiplier-1;
}
console.log("Crashed # " + totalMultiplier.toFixed(2));
}
</script>
<button onclick="crashPoint()">
Try me!
</button>
Kind regards.
Have you tried to use setInterval instead of a loop... just call the same function however many times per second you need it to execute.
1/currentTry*100 won't always stay an integer, randomInt will, I just had to make it so randomInt wasn't always an integer anymore which I could do by removing the *100.

How Can I make millisecond Unique?

I'm using NodeJs.
I received constantly request from server.
I'm added some variable like createdTime to it and saved to the database.
when I sorted data by createdTime in some case It is not reliable, It is Repeated
How can I make differentiate between them ?
I do not want to count request.
I do not like to change timestamp's format.
var createdTime = new Date().getTime();
Here's a method of combining a counter with the current time to allow you to have as many as 1000 separate transactions within the same ms that are all uniquely numbered, but still a time-based value.
And, here's a working snippet to illustrate:
// this guarantees a unique time-based id
// as long as you don't have more than 1000
// requests in the same ms
var getTransactionID = (function() {
var lastTime, counter = 0;
return function() {
var now = Date.now();
if (now !== lastTime) {
lastTime = now;
counter = 0;
} else {
++counter;
}
return (now * 1000) + counter;
}
})();
for (var i = 0; i < 100; i++) {
document.write(getTransactionID() + "<br>");
}
If you want something that is likely to work across clusters, you can use process.hrtime() to use the high resolution timer instead of the counter and then make the id be a string that could be parsed into a relative time if needed. Since this requires node.js, I can't make a working snippet here in the browser, but here's the idea:
// this makes a unique time-based id
function getTransactionID () {
var now = Date.now();
var hrtime = process.hrtime();
return now + "." + ((hrtime[0] * 1e9) + hrtime[1]);
}
Due to my low rep I can't add a comment but it looks like you are needing to go beyond milliseconds.Maybe this stackoverflow question can help you
How to get a microtime in Node.js?

Caculating function running time

I want to calculate the average running time of a function in JavaScript like this:
time = 0;
while(1000) {
time1 = performance.now();
function();
time2 = performance.now();
time += (time2-time1);
}
The problem is that only the first loop the time interval is about 60ms and the following loop the interval is nearly zero.
So I changed the code to:
time1 = performance.now();
while(1000000) {
function();
}
time2 = performance.now();
time = (time2-time1);
The running time is about 4 seconds.
I guess maybe it is because of the automatic optimisation.
If it is this case, are there any approaches to close the optimisation?
You've most likely caused the browser to hand off that code to its JIT compiler. The first run is always through the interpreter (slow). Hot code gets put through the JIT and the resulting native (fast) code is then used.
This is automatic and generally out of your hands to control. You can disable the Firefox JIT compiler by using 'with' in a script.
with({}) {}
Add this to the top of your script and the JIT will be disabled for your script.
You can also use console.time and console.endTime function to calculate the running time.
example:
console.time('profile 1');
for ( var i=0; i < 100000; i++) {
var arr = new Array();
}
console.timeEnd('profile 1');//profile 1: 108.492ms
console.time('profile 2');
for ( var i=0; i < 100000; i++) {
var arr = [];
}
console.timeEnd('profile 2');//profile 2: 81.907ms

Javascript: Print Y, X times

I feel like I'm probably making a fundamental mistake here. I'm hoping someone can help me.
function countdown() {
x = 5;
for (i = x; i > 0; i--) {
document.getElementById('display').innerHTML = (i + " ");
}
}
This is a very small, simple replication of the problem I'm having.
I have a long function. Within that function is a variable, in this case: X.
I want to insert something into an element(in this case: #display) X amount of times.
I figured the best way to do this would be with a for loop, counting down from X by 1 and each time inserting the string I want.
But when it runs, it only returns 1. (I would expect it to return "5 4 3 2 1" in this case).
Please can someone explain to me why this doesn't work? I've been racking my brain over it for hours.
Because you are overwriting the content of the element in each iteration, by assigning a new value to innerHTML. You'd have to append instead:
document.getElementById('display').innerHTML += (i + " ");
// ^
which is the same as
document.getElementById('display').innerHTML =
document.getElementById('display').innerHTML + (i + " ");
And of course it would be much better if you just built the string in the loop and set the content after the loop:
var content = '';
for (i = x; i > 0; i--) {
content += (i + " ");
}
document.getElementById('display').innerHTML = content;
This way you avoid searching for the element in the document on every iteration. But .innerHTML is only useful to some degree, you should also have a look at DOM manipulation functions (such as .appendChild), once you are starting to do more evolved manipulations.

Categories