performance - Javascript update time function causes high CPU -
i have following code using display current date , time, , want updated have setinterval update every second. seems causing page taking 25% of cpu , memory takes keeps climbing longer page up.
is there can improve performance of this?
jquery(function($){ (function update_time(){ var months = ["january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december"]; var days = ["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"]; var dt = new date(); var hr = dt.gethours() > 12 ? dt.gethours() - 12 : dt.gethours(); var mi = dt.getminutes() < 10 ? "0" + dt.getminutes() : dt.getminutes(); var sd = dt.getseconds() < 10 ? "0" + dt.getseconds() : dt.getseconds(); var div = dt.getseconds() & 1 ? ":" : " "; $('.hour').text(hr); $('.minute').text(mi); $('.second').text(sd); $('.day').text(days[dt.getday()]); $('.month').text(months[dt.getmonth()]); $('.date').text(dt.getdate()); $('.year').text(dt.getfullyear()); $('.time-divider').text(div); setinterval(update_time, 1000); })(); });
use settimeout
instead of setinterval
.
the comments above have done job explaining why, i'll reiterate.
your current function schedule new setinterval
every time called, on top of existing ones. after 5
seconds you'll have 32
intervals running. every second number doubles.
settimeout
executes callback function once after set amount of time. after 1 second timeout fire , expire, function execute, , new timeout created. rinse , repeat.
jquery(function($){ (function update_time(){ var months = ["january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december"]; var days = ["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"]; var dt = new date(); var hr = dt.gethours() > 12 ? dt.gethours() - 12 : dt.gethours(); var mi = dt.getminutes() < 10 ? "0" + dt.getminutes() : dt.getminutes(); var sd = dt.getseconds() < 10 ? "0" + dt.getseconds() : dt.getseconds(); var div = dt.getseconds() & 1 ? ":" : " "; $('.hour').text(hr); $('.minute').text(mi); $('.second').text(sd); $('.day').text(days[dt.getday()]); $('.month').text(months[dt.getmonth()]); $('.date').text(dt.getdate()); $('.year').text(dt.getfullyear()); $('.time-divider').text(div); settimeout(update_time, 1000); })(); });
Comments
Post a Comment