0
var myVar = uncontrollableNumber;
$("#myButton").click(function(){

    myVar++;

});

Is there a way that I can check that "if myVar doesn't change (can go up or down, code is just an example) in 20 seconds, do something, and if it does change, restart countdown"? I have tried some code but failed.

function myFunction(myVar){
    var oldMyVar = myVar;
    while(oldMyVar === myVar){
        var countdownDone = false;
        //countdown then run function
        countdownDone = true;
    }
if(!countdownDone){
    myFunction();
}
fetus
  • 23
  • 4
  • Have you tried `setTimeout()`? Do you want to do something the instant it changes, or do something after 20 seconds if at that point it is different to what it was originally? – nnnnnn Mar 02 '16 at 07:15
  • @nnnnnn I am still quite a noob at code, but in my experience I couldn't find a way to **efficiently** restart the countdown if the variable changed. – fetus Mar 02 '16 at 07:18

2 Answers2

1

In order to fire an event on variable change you should use

 object.watch

For details pls refer - Listening for variable changes in JavaScript or jQuery

Community
  • 1
  • 1
khushboo29
  • 797
  • 4
  • 13
  • Also mention [__Browser compatibility__](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/watch#Browser_compatibility) – Rayon Mar 02 '16 at 07:19
  • User this looks amazing and I'll look more into it, maybe implement it once I finish, but I am too nooby and don't understand all the concepts which are stated. And, as the comment says above me, it only seems to work for firefox so that is a nope. Thanks for bringing it to my attention. – fetus Mar 02 '16 at 07:25
  • Yes you are right..if it is intended to support cross browser support, above is not the solution to trust. – khushboo29 Mar 02 '16 at 07:30
1

Here is a working JS fiddle for you.

Also adding a code snippet

var myVar = 0;
var oldVar = 0;
$("#myButton").click(function(){
    myVar++;
});

setInterval(function(){  
  checkForChanges(); // after every 2 secs check
  oldVar = myVar; // reset the old value now to the new one, so during next check we should have our myVar changed.
},2000);

function checkForChanges(){
  if(oldVar === myVar){
  $('#response').append('same value nothing has changed!!'+'<br/>');
    //alert('same value nothing has changed!!');
  }
  else{
  $('#response').append('The value changed!!'+'<br/>');
   //alert('The value changed!!');
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="myButton">
 click Me For Change!!
</button>

<div id="response">

</div>
ForestWow
  • 26
  • 2