Javascript refresh time function causes high CPU performance

I have the following code that I am using to display the current date and time and I want it to be always updated, so I have a setInterval to update it every second. This seems to result in the page taking up 25% of the cpu, and the memory it occupies just keeps going up longer than the page up.

Is there anything I can do to improve performance?

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);
    })();
});

      

+3


source to share


1 answer


Use setTimeout

instead setInterval

.

The comments above did a good job of explaining why, but I'll repeat.

Your current function will schedule a new setInterval

one every time it is called, on top of all existing ones. After just 5

seconds, you will have a run 32

. This number doubles every second.



setTimeout

executes its callback function once after a certain amount of time. So after one second the timeout will fire and expire, the function will execute and a new timeout will be created. Rinse and 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);
    })();
});

      

+5


source







All Articles