jquery - Browser keeps crashing on certain Javascript file -


first off, sorry bad english it's not primary language.

i'm having troubles javascript. file keeps crashing browser (doesn't matter if it's chrome, firefox or ie) after few minutes.

$().ready(function() { timeago(); });  function timeago() {     $('time.time-ago').each(function() {     //get datetime attribute     var ago = $(this).attr('datetime');      //split can convert date object firefox doesn't allow raw input     var spl = ago.split(' ');      var date = spl[0].split('-');      var time = spl[1].split(':');      //convert object     ago = new date(date[0],date[1]-1,date[2],time[0],time[1],time[2]);      //get current date     var = new date();      //calculate difference in days     var days = dayyear(now) - dayyear(ago);      if(days < 0) days += 365;      var out = '';      //get propper string     if(days > 0) {         if(days == 1) {             out = 'gisteren';         }else if(days < 7) {             out = days +' dagen geleden';         }else if(days < 14) {             out = 'een week geleden';         }else{             out = ago.tolocaledatestring('nl-nl',{day: "numeric",month: "short",year: "numeric"});         }     }else{         var dif = math.round((now - ago)/1000);         if(dif < 10) {             out = 'zojuist';         }else if(dif < 60) {             out = 'enkele seconden geleden';         }else if(dif < 120) {             out = 'een minuut geleden';         }else if(dif < 60 * 60) {             out = math.floor(dif/60)+' minuten geleden';         }else if(dif < 60 * 60 * 2) {             out = 'een uur geleden';         }else{             out = math.floor(dif/60/60)+' uur geleden';         }     }     $(this).html(out); }); setinterval(function(){timeago()},10000); }  function dayyear(now) { var first = new date(now.getfullyear(),0,1); var day = math.round(((now - first) / 1000 / 60 / 60 /24) + 0.5); return day; } 

i call example following code.

<time datetime="2013-05-12 19:12:15"></time> 

thanks in advance.

the reason keep calling setinterval inside every loop.

you should use settimeout instead (or call setinterval once)

the difference setinterval executes given every x milliseconds. settimeoutexecutes given code after x milliseconds (once).

since call setinterval inside timeago method, after while have lot of timers running, spawning new timers , amount of timers grow exponentially, resulting in crash.


Comments

Popular posts from this blog

php - cannot display multiple markers in google maps v3 from traceroute result -

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -

javascript - firefox memory leak -