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

时间:2016-03-02 07:11:05

标签: javascript jquery duration

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

    myVar++;

});

有没有办法我可以检查"如果myVar在20秒内没有改变(可以上升或下降,代码只是一个例子),做一些事情,如果它确实改变了,重启倒计时"?我尝试了一些代码但失败了。

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

2 个答案:

答案 0 :(得分:1)

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

 object.watch

有关详细信息,请参阅 - Listening for variable changes in JavaScript or jQuery

答案 1 :(得分:0)

这是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>