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 ("visibilityState" in document 11 && document.visibilityState == "hidden") 12 return false; 13 if ("webkitVisibilityState" in document 14 && document.webkitVisibilityState == "hidden") 15 return false; 16 if ("mozVisibilityState" in document 17 && document.mozVisibilityState == "hidden") 18 return false; 19 if ("msVisibilityState" in document 20 && document.msVisibilityState == "hidden") 21 return false; 22 return true; 23 } 24 25 var timerId = 0; 26 function loop() { 27 timerId = 0; 28 if (!visible()) 29 return; 30 busyLoop(250); 31 timerId = window.setTimeout(loop, 50); 32 } 33 34 function handler() { 35 if (visible() && !timerId) 36 timerId = window.setTimeout(loop, 50); 37 } 38 39 if ("visibilityState" in document) { 40 document.addEventListener("visibilitychange", handler, false); 41 } else if ("webkitVisibilityState" in document) { 42 document.addEventListener("webkitvisibilitychange", handler, false); 43 } else if ("mozVisibilityState" in document) { 44 document.addEventListener("mozvisibilitychange", handler, false); 45 } else if ("msVisibilityState" in document) { 46 document.addEventListener("msvisibilitychange", handler, false); 47 } 48 49 loop(); 50