0

I have a setTimeout and clearTimeout where the setTimeout is working fine but clearTimeout is not working, can anyone help me?

code:

<script type="text/javascript">
  var i = 0;
  var status = setTimeout(function () {
    if (i <= 2) {
      metrics_status();
      i++;
    } else {
      clearTimeout(status);
    };
  }, 3000);
</script>
<div id="ReloadMetrics"></div>
Joseph
  • 117,725
  • 30
  • 181
  • 234
user1642408
  • 11
  • 1
  • 6

5 Answers5

0

You should use clearTimeout outside setTimeout like this

var status;
if(status){ 
   clearTimeout(status);
}
status = setTimeout(function () { }

Example1 Example2

Hary
  • 5,690
  • 7
  • 42
  • 79
  • with out intializing status can we call clearTimeout(status) ? – 999k Feb 08 '13 at 04:11
  • 1
    @Toms Passing an invalid ID to clearTimeout does not have any effect (and doesn't throw an exception). [source](https://developer.mozilla.org/en-US/docs/DOM/window.clearTimeout) – Seain Malkin Feb 08 '13 at 04:26
  • Thats what i am doing here , is still i am missing anything? – user1642408 Feb 08 '13 at 04:38
  • – user1642408 Feb 08 '13 at 04:39
  • @user1642408, Read all the comments, you're using the `clearTimout` inside `setTimeout` and you must use it outside of it – Hary Feb 08 '13 at 04:40
  • thanks, is still i am missing anything?
    – user1642408 Feb 08 '13 at 05:26
0

I assume you need setInterval instead. which will call your function in specified intervals, until you call the clearInterval

Headshota
  • 21,021
  • 11
  • 61
  • 82
0

setTimeout function called only once if it is recursive then you need to call clearTimeout To call a function multiple times then you use setInterval then you can call clearTimeout

Example of setTimeout and clearTimeout is http://www.w3schools.com/jsref/met_win_cleartimeout.asp

Timing functions http://www.w3schools.com/js/js_timing.asp

Rohan Kumar
  • 40,431
  • 11
  • 76
  • 106
0

I think this will do your purpose. please check

<script type="text/javascript">
  var i = 0;
  var status;
  status = setTimeout(Fun, 3000);
  function Fun() {
    if (i <= 2) {
      metrics_status();
      i++;
      status = setTimeout(Fun, 3000);

    } else {
      //clearTimeout(status);
    };
  }
</script>
<div id="ReloadMetrics"></div>
999k
  • 6,257
  • 2
  • 29
  • 32
0

take a look on the given example http://jsfiddle.net/jogesh_pi/qTGPT/

<div id="status"></div>

JS:

var i = 0;
var status = setInterval(function() {
    if (i <= 5) {
        //metrics_status();
        document.getElementById('status').innerHTML = i;
    } else {
      document.getElementById('status').innerHTML = "done";
      _clearTime();
    }
    i++;
  }, 1000);

function _clearTime(){
    return clearInterval(status);
}

hope this should work according to your need..

jogesh_pi
  • 9,762
  • 4
  • 37
  • 65