简体   繁体   中英

Pausing Javascript animation on minimize

I am using the Chart.js library for my animated graphs on the website. From reading other discussions on the subject, browsers treat SetInterval() code differently when a tab is inactive or minimized.

I noticed one suggestion stating that stopping the animation and restarting it when the tab regains focus should correct the issue. I am not sure how to do this nor can I find any code. The library has "animation: true" where I believe this can be used to stop/start it, but not sure how to implement it.

setInterval(function()
{
    $.ajax({
        type: "POST",
        url: "<?= $data['baseUrl']; ?>" +  "graphs.json",
        data: { 'action': 'getServerStats' },
        dataType: 'json',
        success: function(data)
        {
            ram = data['result']['RAMUsageMB'];

            // Add two random numbers for each dataset
            ramGraph.addData([ram], '');

            // Remove the first point so we dont just add values forever
            ramGraph.removeData();
        }
    });
}, 1000);
document.addEventListener("visibilitychange", function() {
  animation = ! document.hidden;
}, false);

https://developer.mozilla.org/en-US/docs/Web/Guide/User_experience/Using_the_Page_Visibility_API Works in IE 10+, Firefox 18+ and Chrome 33+ (according to source). You'll have to change the animation = !document.hidden; yourself as you were a bit vague on this topic, but this should give you an idea.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM