1 // Copyright (c) 2012 The Chromium Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 function busyLoop(millis) { 6 for (var d = Date.now(); Date.now() - d < millis; ) { } 7 } 8 9 function visible() { 10 if ("webkitVisibilityState" in document 11 && document.webkitVisibilityState == "hidden") 12 return false; 13 if ("mozVisibilityState" in document 14 && document.mozVisibilityState == "hidden") 15 return false; 16 if ("msVisibilityState" in document 17 && document.msVisibilityState == "hidden") 18 return false; 19 return true; 20 } 21 22 var timerId = 0; 23 function loop() { 24 timerId = 0; 25 if (!visible()) 26 return; 27 busyLoop(250); 28 timerId = window.setTimeout(loop, 50); 29 } 30 31 function handler() { 32 if (visible() && !timerId) 33 timerId = window.setTimeout(loop, 50); 34 } 35 36 document.addEventListener("webkitvisibilitychange", handler, false); 37 document.addEventListener("mozvisibilitychange", handler, false); 38 document.addEventListener("msvisibilitychange", handler, false); 39 40 loop(); 41