I want to know what condition to write in while loop - javascript

var understand = true;
while(/* ... */) {
console.log("I'm learning while loops!");
understand = false;
}
I want to print "I'm learning while loops!" so what condition need to write in loop?

Try this:
while(understand){
console.log("I'm learning while loops!");
understand = false;
}
Edit1:
If you want your loop to run for number of times:
var i=0;
while(i<10){ //suppose you want to run your loop for 10 times.
console.log("I'm learning while loops!");
i++;
}
Edit2: (Reply to code in comments)
You are using loop as a function name and checking same in the while loop which is wrong.
Try this:
var myFunctionName = function()
{
var myVariableName = 0;
while(myVariableName<3)
{
console.log("In loop" + myVariableName);
myVariableName++;
}
};
myFunctionName();

Try this to execute your while loop once.
var understand = false; // not yet
while(understand !== true){
console.log("I'm learning while loops!");
understand = true; // I do now!
}

var understand = true;
while( understand == true){
console.log("I'm learning while loops!");
understand = false;
}

The while loop will continue to execute while the condition evaluates to true. So it really depends on the condition you want. If you just want a single loop, and judging by your code, you probably want the following:
var understand = true;
while(understand) {
console.log("I'm learning while loops!");
understand = false;
}
This is like saying: "while understand equals true, then execute the loop"
It is worth mentioning that the variable name understand doesn't make much sense starting as true and being set to false when you want to break the loop (assuming that you want to break the loop when you do understand). So the following would be more logical:
var understand = false;//don't yet understand, so enter loop
while(!understand) {
console.log("I'm learning while loops!");
understand = true;//now I understand, so break loop
}
This is like saying: "while understand equals false, then execute the loop"

Related

How to use break statement in Typescript

I'm new to Javascript. I started with a very basic project in Angular i.e. Form validation. In my case I've to call my custom method, validationTest() within itself only once. If I do not put any break condition then there will be too many recursions. I have to stop this. I tried many other solutions:
Break Statement in TypeScript
TypeScript - Loops
I followed them very carefully, but I'm getting this:
Module parse failed: Unsyntactic break (84:12)
Here's my code:
validationTest() {
let count =0;
this.isAnyRangeInvalid = false;
this.monthpicker.forEach(picker => {
if (picker.isValidRange === false) {
this.isAnyRangeInvalid = true;
}
});
count ++;
if(count===1) {
break;
}
this.validationTest();
}
Even VScode editor is also showing a red zig-zag line under the token break.
I'm coming from Java and CPP background. Please correct me.
To stop a function from executing, use return. break only makes sense in the context of a for or while loop.
But another problem is that your validationTest doesn't have a persistent view of the count variable - it's completely local, so the test isn't going to work anyway. Consider passing a parameter instead, which will indicate whether the current call is recursive or not:
validationTest(lastTry = false) {
this.isAnyRangeInvalid = false;
this.monthpicker.forEach(picker => {
if (picker.isValidRange === false) {
this.isAnyRangeInvalid = true;
}
});
if (!lastTry) this.validationTest(true);
}
Make sure that the initial call of validationTest doesn't pass a parameter, or passes false.
For a more general solution of limiting yourself to N recursive tries, you can pass around a number instead, eg:
validationTest(triesLeft = 3) {
this.isAnyRangeInvalid = false;
this.monthpicker.forEach(picker => {
if (picker.isValidRange === false) {
this.isAnyRangeInvalid = true;
}
});
if (triesLeft !== 0) this.validationTest(triesLeft - 1);
}

increment not working in controller

$scope.isChecked = function(id){
var i=0,j=0,k=0;
//$scope.abc[i].usertype[j].keywords[0].key_bool=true;
if($scope.abc[i].type_selected == true){
while($scope.abc[i].usertype.length){
while($scope.abc[i].usertype[j].keywords.length){
if($scope.abc[i].usertype[j].keywords[k]._id == id){
if($scope.abc[i].usertype[j].keywords[k].key_bool == true){
$scope.abc[i].usertype[j].keywords[k].key_bool = false;
return false;
}
else{
$scope.abc[i].usertype[j].keywords[k].key_bool = true;
return true;
}
}
k++;
}
j++;
}
}
};
Incrementing k++ is working while incrementing j++ not, can someone explain me this, why such happening?
isChecked function called whenever checkbox is checked/unchecked as:
ng-click="isChecked(l._id)"
Everything works perfectly for 'j=0', but not for later 'j' values.
Simply because of the return statements execution gets out of the function every time a return statement is reached. So j++; is unreachable every time the if statement is executed
for j=0, it goes inside the inner while loop, and when it reaches to the return statement, it comes out of function.
That is why, outer while loop is not getting executed again.
To get more about return, read this
i got the answer.
we have to put k=0; between the 2 while loops.
still thanks guys for ur help

Javascript inheritance infinite loop

I create this block of code in javascript:
function Shape() {}
Shape.prototype.name = "Shape";
Shape.prototype.toString = function() {
result = [];
if(this.constructor.uber) {
result[result.length] = this.constructor.uber.toString();
}
result[result.length] = this.name;
return result.join(', ');
}
function twoDShape() {};
twoDShape.prototype = new Shape();
twoDShape.prototype.constructor = twoDShape;
twoDShape.uber = twoDShape.prototype;
twoDShape.name = "twoD Shape";
var a = new twoDShape();
console.log(a.toString());
I don't know why but when I run it, firefox is freeze. I've been trying hours to figure it out. And my guess is there should be an infinite loops in my code and it lives somewhere in the if condition, but I didn't find it out. Could someone help me out of this headache.
Thank you!
When you call this.constructor.uber.toString() from Shape.prototype.toString, uber is twoDShape.prototype which is a Shape, and so that toString method is Shape.prototype.toString again.
And that causes an infinite loop.
well, after trying a fair amount of test, I finally got a clue. And I believe this is a answer for my own question above. Typing: a.constructor.uber.constructor === twoDShape in firefox, it returns true. And that's why it causes infinite loop.

How to break from objx(data).each(function(item) iteration?

How to break from objx(data).each(function(item) iteration when a certain condition is met.
My Json string is below:
var data= [{"field1": "0","field2": "2"},{"field1": "7","field2": "2"},{"field1": "1","field2": "5"}];
Here is a my code:
function iterate(){
objx(data).each(function(item){
if(item.field1 == "7"){
//doing some job;
return;
}
alert("after if is executed");// this alert coming inspite of giving
}); // return in if block
}
i think the return is only enabling it to come out of function but not from the loop. i dont want this unnecessary iteration once my condition is met and job is done.
can anyone suggest how to come out of this each loop?
return false;
Returning false breaks out of the each function.
To exit the jquery each loop
function iterate(){
objx(data).each(function(item){
if(item.field1 == "7"){
//to stop the loop here
return false; // here - will exit the each loop
}
});
}

Sleep in javascript - no setTimeout [duplicate]

This question already has answers here:
What is the JavaScript version of sleep()?
(91 answers)
Closed 7 years ago.
All those setTimeout answers here don't work!
I just want to wait a few seconds between two functions, like this:
do_fn1();
wait(5000);
do_fn2();
From phpied.com:
function sleep(milliseconds) {
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > milliseconds){
break;
}
}
}
I don't think you can. You'll probably have to
do_fn1();
window.setTimeout(do_fn2, 5000);
Two thoughts:
first of all why not wrap up all of the post delay statements into a wrapper function
var postDelayFunc = function(){
dosomething();
dosomethingelse();
onemorething();
}
then in your code pass this function as the parameter to setTimeout.
//your code
dofunc1();
setTimeout(postDelayFunc, 1000);
Alternatively take a look at jQuery deferred: http://msdn.microsoft.com/en-us/scriptjunkie/gg723713, although you will probably end up writing very similar code.
One thing struck me though about your responses to other answers and possibly where the confusion arises. I think you are looking at your function and seeing a single thread you just want to hold up for a while before carrying on.
You should not do this though in javascript as it ties up the entire browser and will annoy the hell out of users. Instead what you are in effect doing when you use setTimeout, is indicating that when the timeout expires another thread will pick up and execute the passed in function.
As soon as the timeout has been set, the executing thread will continue with the next line (which is why you think the timeout isn't working). What you probably need to do, is set the timeout, and put ALL the post-execution steps into the function handed off to the timer as indicated above.
Saying they all don't work without an example is big call because I'm sure they probably do.
How about this,
do_fn1();
setTimeout(do_fn2, 5000);
All those setTimeout answers here don't work!
Of course they do:
function a() {
alert("I'm pretty sure...");
}
function b() {
alert("...that they work just fine.");
}
a();
setTimeout(b, 5000);
Another hack I will probably use, however personally I would not recommend it.
Check out here http://jsfiddle.net/S6Ks8/1/
function parseSleeps(func){
var fdef = func.toString();
var fbody = fdef.match(/\{([\s\S]*)\}/)[1].split(/sleep\(.*?\)\;?/);
var sleeps = fdef.match(/sleep\((.*?)\)/g);
var fargs = fdef.match(/\(([\s\S]*?)\)/)[1];
var fbodyNew = [];
var times = [];
fbodyNew.push(fbody.shift(), '\n');
for(var i = 0; sleeps && i < sleeps.length; i++){
var sec = sleeps[i].match(/\d+/)[0];
times.push(sec);
fbodyNew.push('setTimeout(function(){\n');
fbodyNew.push(fbody.shift(), '\n');
}
while(times.length){
var sec = times.pop();
fbodyNew.push('}, ', sec, ');\n');
}
return new Function(fargs, fbodyNew.join(''));
}
// Your code from here
function a(str1, str2){
alert(str1);
sleep(3000);
alert(str2);
}
var func = parseSleeps(a);
func('here', 'there');
The smartest way would be to have something like
function a() {
// Do stuff
setTimeout(b, 42)
}
function b() {
// Do other stuff delayed
}
Never "block" any Threads in JS - if you think you have to do there is definately a "cleaner" way to do achieve your aim.

Categories