Simple Looping In Java Script - javascript

I made a simple loop and would like to know how to carry this out.
The variable's name is Math, and it is equal to 4. I am trying to write a simple looping statement that says: "While Math is not equal to 4, await your number"
Here is the code I have so far:
var math = 2+2;
var loop = function(){
for(var i=0; i < 5; i++)
{
while (math[i] != 4)
{
console.log ("Await until you reach 4");
}
}
};
loop();

The following code will do what you presumably want:
var math = 2+2;
var loop = function(){
var i = 0;
while (i !== math) {
i++;
console.log ("Await until you reach 4");
}
}
loop();
Note that technically, the for loop in javascript (as well as in many other languages) actually is not that much different from a while loop, as the code for initialization, increment and termination is rather unrestricted. You are not even forced to have an iteration variable in you for loop.
The difference is in someone else's ease of understanding of your code (or your's after you haven't looked into you code for some time). for suggests a counted iteration of a list, while some operations to be performed while (sic!) a condition is fulfilled without which the operation make no sense or produce the wrong result.

This concept will create an endless loop, that waits for something to edit the variable.
As javascript occupies the thread its running in, all events will be waiting for this endless loop to end.
If it's part of the main GUI thread, (normal javascript) this means that your page will hang. Only use this method for webworkers, or extensions.
Instead redesign as eventhandlers, instead of a main loop
edit: having read your comments, and found out what you are trying to do:
var math = 2+2;
for(var i = 0; i < 5; i++){
if(i != math){
console.log ("Await until you reach 4");
continue
}
alert("yay")
}
or with a while loop
var math = 2+2;
var i = 0;
while(math != i){
if(i != math){
console.log ("Await until you reach 4");
}
i++;
}
alert("yay")

Maybe this is what you are trying to do:
var math = 2+2;
var loop = function(){
for(var i=0; i < 5; i++){
if(i != math){
console.log ("Await until you reach 4");
}else{
console.log("You have reached 4");
}
};
loop();
Using while
var math = 2+2;
var loop = function(){
var i=0;
while(i != math){
console.log ("Await until you reach 4");
i++;
}
};
loop();

var loop = function(math){
var i = 0;
while(i!==math){
console.log ("Await until you reach 4");
i++;
}
}
loop(2+2);

Related

javascript node.js How to avoid While(true) in this situation?

I have read that use of 'while(true)' is a big no-no and use of 'while(condition)' or 'do...while(condition)' is recommended(1).
Can you tell me how to do that here -
while (true){
get some data;
if(condition based on data above), do something;
else(break);
} //repeat until break reached
I could use 'do...while' (see below) but that repeats the 'if' condition so this doesn't seem to be the best option -
do{
get some data; //must happen first to get info to create condition
if(condition based on data above), do something;
} while(condition based on data above);
It can be more simple like this, with an example:
var x = 0;
console.log("Entering loop");
while(true){
// always make sure to update something in your condition
// so you dont fall into an infinite loop
x++;
console.log(x); // mostly demostrative
if(x===3) break; // condition to determine when should the loop stop
}
console.log("Out of the loop");
There is no problem using while(true).
The no-no you read is because it is a potential issue that can be resulted into an infinite loop.
So if this is the case, you can use a counter to break the loop if nothing happens until that. for eg, max_attempt = 100.
Why not just do:
for(get some data; condition based on data above; get some data;) {
do something;
}
E.g.:
for(var i = Math.random(); i < .8; i = Math.random()) {
console.log(i);
}
I would use something like this:
while (condition based on data above){
get some data;
do_something;
}
Example:
while (variable_boolean == false && variable_num <= 10){
variable_2 = variable_num * 5;
}

Is there a way to save processing cycles with static if-statements inside loops?

Consider this code snippet:
var x = 10;
for (var i=0; i<100; i++) {
if (x === 10) {
/* do some stuff */
}
}
The condition within the if-statement is static except for x, whose value is evaluated only once just before entering the loop. This value could come from anywhere - it can be hard coded, an input from the user, the result of a math problem, etc. The point is that once x is evaluated, it doesn't change. Therefore, the condition inside the if-statement would be the same at every loop iteration, but the code clearly evaluates the condition nonetheless, wasting processing cycles in the process. Is there a way to make the condition evaluate once and have every iteration afterwards immediately execute the right code branch?
One option is to save the condition in advance, so that you don't need to re-check x every time:
var x = 10;
var doCondition = x === 10;
for (var i=0; i<100; i++) {
if (doCondition) {
/* do some stuff */
}
}
Another option is to have two separate functions, one for if the condition is fulfilled, and one for when it's not. It'd be WET, but the condition would only be evaluated once. Eg, you could turn
var x = 10;
var doCondition = x === 10;
for (var i=0; i<100; i++) {
if (doCondition) {
/* do some stuff */
} else {
// do some other stuff
}
}
into
const fns = {
trueCond() {
for (var i=0; i<100; i++) {
// do some stuff
}
},
falseCond() {
for (var i=0; i<100; i++) {
// do some other stuff
}
}
// insert other conditions here, if you want
// could also just use if/else statements containing loops,
// rather than an object of functions
};
const fn = x === 10 ? fns.trueCond : fns.falseCond;
fn();
It depends on how complicated the loop is / what other operations are being performed.
Still, this is almost always a case of premature optimization - if you're worried about performance, run a performance test first, and if you find things are slow, identify a slow area of code and improve it. A condition in a loop probably won't be the slowest area.

Counting unknown/dynamic array length of class element

I wrote a simple code/userscript to notify me about changes on a webiste:
function notifier(){
setTimeout(function () {
location.reload(true);
},60000)
}
function notiCounter() {
console.log("Counting notifications");
var noti = document.getElementsByClassName("notification");
for(var i = 0; i < 2; i++) {
if(noti[i].innerHTML != undefined) {
console.log(noti[i].innerHTML);
notifications++;
console.log("Notifications: " + notifications);
}
}
}
function notification(){
setTimeout(function () {
notiCounter();
if(notifications > 0){
document.title = "(" + notifications + ") new notifcations";
sound.play();
}
notifier();
},50)
}
notification();
The problem is, that the actual final number of noti[i] is unknown/dynamic and changes all the time, so if i < 2 is replaced with a higher number the for loop ends up in an infinite loop - and if I pick it too low (2 for example), data will gets lost if the actual number is above 2.
Any idea about that problem? Maybe it's really obvious and I can't see, as it is really late haha.
Rather than checking for i < 2, check for i < noti.length. Or you can iterate through using a for(var i in noti) type loop. Or better yet, if you just want the number of notifications directly, just use the value in noti.length

Run a for loop. Increment the value; exit and begin loop again with new value

I want to run a loop. I want it to excecute it 16 times like,
for (var i = 0; i <= 15; i++) {
alert(i);
}
I want this loop to run on clicking a button. But the loop should only return the first value of i and then exit. Like this,
for (var i = 0; i <= 15; i++) {
alert(i);
exit();
}
What I am confused with is, whenever I click the button I want this loop to run-only once-but with the value being incremented by one. The whole idea is to alert the i value on each click of the button but incremented by one each time. I think even my use of for loop also is not making any sense. Or is my whole logic wrong. I think I am doing something more complex where something simple like using counter will accomplish the same. Any help appreciated.
var myVal = 0;
function incrementValue(){
myVal++;
alert(myVal);
}
Just increment a variable every time you call the function.
If I am getting it right, it should be somewhat like this,
var btn_init = 0;
//on click
$(function(){
$('#your_button_id').on('click',function(){
btn_init++; //increment
alert(btn_init);
}
});
<div class="button1">click</div>
<div class="valuecontainer"></div>
<script>
var i=0;
var x=15;
$('.button1').click(function(){
if(i<x){
i++;
$('.valuecontainer').html(i);
}
else
{
alert("rechaed limit");
}
});
</script>
I guess you will find your answer here:
Count function call in JS
This is the shortest code found there though i donot completely understand this (somebody plz explain):
function myFunction() {
this.num = (this.num || 0) + 1;
if(this.num <= 15)
alert(this.num);
}

Appending to empty element does not work

I want to display the characters of a string, stored in an array, one by one.
When I call threadsleep(a) using the following code: http://jsfiddle.net/thefiddler99/re3qpuoo/, it appears all at once.
The problem lies somewhere here I presume
for (var i = 0; i < str.length; i++) {
$('#hello').append(str[i])
alert("foo")
sleep(500)
};
The alert shows that everything is working properly except that the interval between each is not present.
I cannot figure out why.
Note: Sleep is a function I have defined that works for the set amount of time
JavaScript is single threaded. It is too busy running round and round your while loop to perform a repaint of the page.
Don't try to write a sleep function. The language isn't suited to it and it just chomps CPU. Rewrite your code to use setInterval or setTimeout instead.
var i = 0;
next();
function next() {
$('#hello').append(str[i]);
i++;
if (i < str.length) {
setTimeout(next, 500);
}
}
Just try with setTimeOut recursion call.
Demo
<script>
var text="This string will be display one by one.";
var delay=500;
var elem = $("#oneByOne");
var addTextByDelay = function(text,elem,delay){
if(!delay){
delay = 500;
}
if(text.length >0){
//append first character
elem.append(text[0]);
setTimeout(
function(){
//Slice text by 1 character and call function again
addTextByDelay(text.slice(1),elem,delay);
},delay
);
}
}
addTextByDelay(text,elem,delay);
</script>

Categories