1

I just want to know why setInterval() and setTimeout() not matching time result ?

Syntax :

setInterval(code,millisec,lang)
setTimeout(code,millisec,lang)

and both using millisecond..

Why I get random i all the time ?

So my test function look like...

var i = 0;

$("button").click(function() {

  var run = setInterval(function(){
    i++; $("code").html(i);
  },0);

  setTimeout(function(){
    clearInterval(run);
    i = 0;
  },2000);


});

Why result not showing 2000 ? or what I misunderstand something ?

If min. value for setInterval() is 4ms why I don't get same result ?

Playground : http://jsbin.com/ezeliz/1/edit

l2aelba
  • 21,591
  • 22
  • 102
  • 138
  • Is your question, why the interval loop is not reaching 2000? – Yoshi Feb 15 '13 at 12:49
  • yes , your understand right :D @Yoshi – l2aelba Feb 15 '13 at 12:54
  • 1
    Well, then the answer is simple. Even if you *request* an interval length of 0 milliseconds, you're not guaranteed to get it and thus should not rely on the set value. If what you're doing is timesensible, you'll need to keep track of time differences between calls yourself. – Yoshi Feb 15 '13 at 12:57
  • Offcourse it doesn't! [This information](http://javascript.about.com/library/blstvsi.htm) could be helpfull. – Ron van der Heijden Feb 15 '13 at 13:44

1 Answers1

1

What is setInterval(…, 0) supposed to do? It can't repeat the function after zero time, there will always be a small delay. Actually, that delay is even standardized to a minimum value of 4ms. Opera 12 for example counts (nearly) to 500 in 2s, which would match that, other browsers might have a larger delay (they are free to choose one).

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375