一直知道在js里面使用计时器会阻塞ui渲染,并且在移动端锁屏后计时器不会继续执行。网络上常用的思路是启动定时器时记录当前时间,当锁屏进来后通过当前时间和记录时间对比去解决锁屏后不继续执行的问题,个人觉得这种解决办法不优雅。 最近看了关于worker的知识,就想着用worker写是不是能解决这个问题,试了试,还真行,代码附上。
worker.js
function timeout(time) { var clock=setInterval(function() { time=time*1 - 1; if (time != 0) { postMessage(time); }else{ clearInterval(clock); } }, 1000); } this.addEventListener("message", function(e){ timeout(e.data); });
页面
<!DOCTYPE HTML> <html> <head> <meta charset="UTF-8"> <title>1</title> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="renderer" content="webkit"> <meta name="viewport" content="width=device-width,initial-scale=1.0, maximum-scale=1.0,minimum-scale=1.0,user-scalable=no"> <meta content="telephone=no" name="format-detection"> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <!-- <link rel="stylesheet" type="text/css" href="../../css/base/shoppingBag.css"> --> </head> <body> <div id="count" style="font-size: 18px;color: red;height: 35px;line-height: 35px;width: 100%;text-align: center;">60</div> <div id="button" style="height: 35px;line-height:35px;text-align: center;padding: 10px 20px;background-color: green;">按钮</div> </body> </html> <script src="http://code.jquery.com/jquery-latest.js"></script> <script type="text/javascript"> $(function(){ var myworker= new Worker("work.js"); $('#button').on('click',function(e){ myworker.postMessage(60); }); myworker.addEventListener("message", function(e){ $('#count').html(e.data) }); }); </script>