-1

I am trying number counter animation for displaying the value of an element and setTimeout() works as the specified time in firefox but for some reason in IE it is invoked quickly.

Jsfiddle Code

The below is my code..

$('document').ready(function() {
  var i=1,data=10;
  my_int=setInterval(
     function () { 
        if(i<=data)
          $('p').text(i++);
        else
          $('body').append("overflow"); }
     ,64);
setTimeout(function() { $('body').append("done");clearInterval(my_int); },64*data);
});

By quickly I mean in IE setInterval() is executed 8 times and then it is invoking the timeout function (while it should loop for 10 times).

I have also gone through these question but none of them helped. one two

is it a problem in IE or is it problem with my code itself ??

Community
  • 1
  • 1

1 Answers1

1

I'm going to guess that this is a race condition and suggest that maybe this is a better way to achieve the same thing:

$('document').ready(function() {
    var i = 1, data = 10;
    my_int = setInterval(function () {
        if (i <= data) {
            $('p').text(i++);
        }
        else {
            $('body').append("overflow").append("done");
            clearInterval(my_int);
        }
    }, 64);
});

To answer your actual question, it is likely a problem with your code that is only apparent due to the nature of IE's timing system. Your code depends on timings, but these timings are not guaranteed. When you say, "do this every X milliseconds", what actually happens is that the system will try to execute your code as close to the requested time as it can. However, it may fail to do this when there are other events to run and the execution of these events makes them run over your requested time.

Artyom Neustroev
  • 8,627
  • 5
  • 33
  • 57
Tom
  • 522
  • 3
  • 13
  • Perfect..the best thing about the answer is the explanation about the race condition..thanks @Tom.. :) Just out of curiosity in [this question](http://stackoverflow.com/questions/24336913/) won't there be the same issue of **race condition** .. – user2081934 Feb 10 '15 at 03:20