Javascript 检查一段时间内是否没有发生某些事情

Javascript check if something doesn't happen over a period of time

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

    myVar++;

});

有什么方法可以检查 "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"?我尝试了一些代码但失败了。

function myFunction(myVar){
    var oldMyVar = myVar;
    while(oldMyVar === myVar){
        var countdownDone = false;
        //countdown then run function
        countdownDone = true;
    }
if(!countdownDone){
    myFunction();
}

要在变量更改时触发事件,您应该使用

 object.watch

详情请参考 - Listening for variable changes in JavaScript or jQuery

这里有一个 working JS fiddle 给你。

同时添加一个代码片段

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>