简体   繁体   中英

Javascript trouble understanding IF loop to use in a script

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM