Javascript trouble understanding IF loop to use in a script - javascript

I'm new at javascript and am using tampermonkey for a website.
What i want to do is monitor a variable on a page and when said variable reaches a certain value, go to another page, do something, and then recheck the value of this variable.
My logic was to:
setInterval(function(){reloadPage1},10000);
var variable = someTextonThisPage;
if(someTextonthisPage meets condition)
{
go to Page2;
execute something on page 2;
setNewValueForVariable; //(or just go back to initial
//and get the new value from there)
}
Now my problem is when the if executes, it goes to page2 keeps looping the if call even if i set the variable to something false.
I tried doing something like:
function doThis()
{
if(condition)
return true;
else return false;
}
if(doThis())
{
goToPage2;
do stuff;
doThis();
}
I end up having the if statement go on and on, going to page 2 and my settimeouts to do something on that page never execute because of the next iteration of the 'if'.
What am i doing horribly wrong in my thought pattern?

Your doThis() function is right. Everything ok with it.
function doThis()
{
if(condition)
return true;
else
return false;
}
But when you check the loop you have to call it one time only. After doing stuff you are again calling doThis() function it is wrong.
if(doThis())
{
goToPage2;
do stuff;
//doThis();
}
And also it depends on how you are calling this loop and functions.
For eg.,
<script>
var i = 0;
onPageLoad()
{
if(i%2==0){
return true;
i++;
}else{
return false;
i++;
}
}
if(onPageLoad()){
goToPage2;
doStuff();
}else{
onPageLoad()
}
</script>
Here when the condition meets the right statement which is i%2 == 0 it will automatically call goToPage2 function otherwise it again going to check the condition.
You can add interval/timeout in the loop to check when the variable is updating and when it calls goToPage2 function.
Hope this helps.

Related

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

How to make part of a function only execute once until it's allowed to do otherwise

How can I call a javascript function (repeatedFunction()) repeatedly but make it so that, let's say an alert("This function is being executed for the first time"), is only activated the first time that repeatedFunction() is, but the //other code is always activated? And also, how can I make the alert() allowed to be activated for one more time, like if the repeatedFunction() was being executed for the first time again?
You can set a flag. Say for example, you have this following code:
var flagAlertExecd = false;
function repeatThis () {
if (!flagAlertExecd) {
alert("Only once...");
flagAlertExecd = true;
}
// Repeating code.
}
And to repeat this code, it is good to use setInterval.
setInterval(repeatThis, 1000);
Functions are objects. You can set (and later clear) a flag on the function if you like:
function repeatedFunction() {
if (!repeatedFunction.suppress) {
alert("This function is being executed for the first time");
repeatedFunction.suppress = true;
}
// ...other code here...
}
When you want to reset that, any code with access to repeatedFunction can clear the repeatedFunction.suppress flag:
repeatedFunction.suppress = false;
The flag doesn't have to be on the function, of course, you could use a separate variable.
That said, I would suggest looking at the larger picture and examining whether the alert in question should really be part of the function at all.
JavaScript closure approach will fit in this task. It has no global variables, and keeps your task in a single function.
var closureFunc = function(){
var numberOfCalls = 0;
return function(){
if(numberOfCalls===0)
{
console.log('first run');
}
numberOfCalls++;
console.log(numberOfCalls);
};
};
var a = closureFunc(); //0
a(); //1
a(); //2
var a = closureFunc(); //drop numberOfCalls to 0
a(); //1
http://jsfiddle.net/hmkuchhn/
You can do it by declaring a variable and incrementing it in your function. Using an if statement, you can check how many times it has been triggered. Code :
var count = 0;
function myfunc(){
if(count==0){
alert("Triggering for the first time");
count++;
}
//Your always triggering code here
}
Demo
This even tracks record of the how many times the function is triggered. It can be useful if you don't want to execute the alert() on nth time.
You can also use boolean values. Like this :
var firstTime = true;
function myfunc(){
if(firstTime){
alert("Triggering for the first time");
firstTime = false;
}
//Your always triggering code here
}
Demo
The second approach will not track the record of how many times the function has been triggered, it will just determine that whether the function is being invoked for the first time or not.
Both the approaches work fine for your purpose.
var firstTime = true;
var myFunction = function() {
if(firstTime) {
alert("This function is being executed for the first time");
firstTime=false;
}else{
//whatever you want to do...
}
}; //firstTime will be true for the first time, after then it will be false
var milliseconds = 1000;
setInterval(myFunction, milliseconds);
//the setInterval means that myFunction is repeated every 1000 milliseconds, ie 1 second.

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
}
});
}

Break out of function within enumarable.each iteration

I have a Prototype class - within the class i call a function and within this function i do en enumerable.each iteration. If an element within this iteration fails a check i then call another function which then re-calls this same function later. Can i break within this iteration so not only the iteration is ended but nothing else within the function is called.
Say with this code i wouldnt want the console.log to be called if elm.something == 'whatever'. Obviously i could set a variable and then check for this after the function but is there something else that i should be doing?
myFunction: function(el){
el.each(function(elm){
if(elm.something == 'whatever'){
this.someOtherFunction(elm);
}
},this);
console.log("i dont want this called if elm.something == 'whatever'");
}
Just to be clear, in this case the console.log is just placeholder code for the beginnings of some additional logic that would get executed after this loop
You answered it yourself
"Obviously i could set a variable and then check for this after the function"
In this case, you're basically looking to not call the console.log even if elm.something == 'whatever' for a single 'elm'
myFunction: function(el){
var logIt = true;
el.each(function(elm){
if(elm.something == 'whatever'){
logIt = false;
this.someOtherFunction(elm);
}
},this);
logIt && console.log("i dont want this called if elm.something == 'whatever'");
}
The simplest way would be to avoid using each() and instead rewrite using a for loop:
myFunction: function(el){
for(var i in el) {
var elm = el[i];
if(elm.something == 'whatever'){
return this.someOtherFunction(elm);
}
}
console.log("i dont want this called if elm.something == 'whatever'");
}

Return statements at the end of a JavaScript function

I have seen in many times in JavaScript code people add a return true at the end although not necessary. Does anyone know why?
var _globalString;
function doSomething()
{
_globalString= _globalString +' do something';
//some codes to do something more
//finally adding a return true
return true;
}
The thing that may have gotten some people into the habit was event handlers for forms, if you have, say:
<form onsubmit="return myfunction();">
and myfunction() returns true, the form submits, else if it returns false it doesn't. People doing it in general could've got the habit from this. Some languages require return values from functions, Javascript doesn't; and having return true at the end of most functions serves no purpose.
In addition to Erik's answer I would like to add
return true / return false are also used when you want boolean value as a return. And based on that return you execute some other function.
A "return" inside a function automatically stops further execution of that function so for example:
function myFunc(){
if(foo == 'bar'){
/* do something */
}else{
/* do something */
}
}
is the same as:
function myFunc(){
if(foo == 'bar'){
/* do something */
return true;
}
/* if foo != 'bar' then whatever follows is executed... */
}
Actually if you are calling the function in onsumbit event
Example
<input type=sumit value=click Onsumbit='return function_name();">
While you are calling like , if the function return true only, form will be submit
If it return false , it wont submit the form
Also you do not need to use return true or false in this case below
var newPage = "http://www.google.com";
function redirectURL(){
window.location.href= newPage;
return true; //no return required
}
It's hard to say why some programmers do certain things.
Maybe it's intended to indicate success/failure, but they haven't added any failing branches yet?

Categories