繁体   English   中英

当浏览器选项卡未激活时如何保持javascript运行

[英]How to keep the javascript running when the browser tab is not active

这是我的代码:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script>

var myseconds = 20;
var mycolor = 'rgba(255, 100, 0, 0.8)';

//alert('You will have '+Math.floor(myseconds/60)+' minutes and '+myseconds%60+' seconds to finish. Press “OK” to begin.');

$(function(){
$('div#pie_to_be').pietimer({
seconds: myseconds,
color: mycolor
},
function(){ $('#caspioform').submit(); });});
(function($){jQuery.fn.pietimer=function(options,callback){var settings={'seconds':10,'color':'rgba(255, 255, 255, 0.8)','height':this.height(),'width':this.width()};if(options){$.extend(settings,options);}this.html('<canvas id="pie_timer" width="'+settings.height+'" height="'+settings.height+'">'+settings.seconds+'</canvas>');var val=360;interval=setInterval(timer,40);function timer(){var canvas=document.getElementById('pie_timer');if(canvas.getContext){val-=(360/settings.seconds)/24;if(val<=0){clearInterval(interval);canvas.width=canvas.width;if(typeof callback=='function'){callback.call();}}else{canvas.width=canvas.width;var ctx=canvas.getContext('2d');var canvas_size=[canvas.width,canvas.height];var radius=Math.min(canvas_size[0],canvas_size[1])/2;var center=[canvas_size[0]/2,canvas_size[1]/2];ctx.beginPath();ctx.moveTo(center[0],center[1]);var start=(3*Math.PI)/2;ctx.arc(center[0],center[1],radius,start-val*(Math.PI/180),start,false);ctx.closePath();ctx.fillStyle=settings.color;ctx.fill();}}}return this;};})(jQuery);
</script>

这是一个饼图计时器,从页面加载开始运行。 但是当我切换浏览器选项卡时,它会在那里暂停。 然后,当我回到该选项卡时,它将从停止的地方继续。 请告诉我如何让它在后台运行(即,即使用户看不到该选项卡)。

不要依赖setInterval计时器是一致的。 即使在前台,它也会有所不同。 相反,当setInterval触发时,请读取实际时间并使用该时间来计算新位置。 这样,计时器似乎将在后台运行,即使不是。

尝试更新jQuery。 较新的版本具有与间隔有关的修复程序。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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