页面增加定时器

来源:互联网 发布:反淘宝 编辑:程序博客网 时间:2024/06/11 01:06

简单定时器:

前几天给页面增加了一个简单的定时功能,但是由于用的settimeout函数,变量设为全局变量,在每次页面加载后都要初始化,所以在实际应用中有点不切实际。我做的这个计时器是给直播中的视频计时的,所以当用户退出后,再进入该页面应该接着前面的计时继续,表明这个直播持续了多久,而不应该清零。所以我决定引入cookie。

加cookie的定时器(刷新后不会清零):

jquery对cookie进行了很好的支持,有相应的扩展插件,但是为了页面不至于加载脚本过多拖慢速度,而且我这个cookie很简单,所以在直接引入了对应的函数,代码如下:

jQuery.cookie = function(name, value, options) {if (typeof value != 'undefined') {  options = options || {};  if (value === null) {  value = '';  options = $.extend({}, options);  options.expires = -1;  }  var expires = '';  if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {  var date;  if (typeof options.expires == 'number') {   date = new Date();   date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));  } else {   date = options.expires;  }  expires = '; expires=' + date.toUTCString();  }  var path = options.path ? '; path=' + (options.path) : '';  var domain = options.domain ? '; domain=' + (options.domain) : '';  var secure = options.secure ? '; secure' : '';  document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');} else {  var cookieValue = null;  if (document.cookie && document.cookie != '') {  var cookies = document.cookie.split(';');  for (var i = 0; i < cookies.length; i++) {   var cookie = jQuery.trim(cookies[i]);   if (cookie.substring(0, name.length + 1) == (name + '=')) {   cookieValue = decodeURIComponent(cookie.substring(name.length + 1));   break;   }  }  }  return cookieValue;}};

我用cookie完成的计时器代码片段如下,供大家参考:

function settime(a){    if(a<10)        a = "0"+a;    return a;} if(($.cookie("cookieH")  == null) && ($.cookie("cookieM")  == null) && ($.cookie("cookieSe") == null) ){ var h =0;  //timer--hour var m =0;  //timer--minute var s =0;  //timer--second } var t =0;  //setTimeout的返回标志function starttime(){    $.cookie("cookieH",h,  {  "path":"/",   "expires":2 });$.cookie("cookieM",m,  {  "path":"/",   "expires":2 });$.cookie("cookieSe",s,  {  "path":"/",   "expires":2 });h = $.cookie("cookieH");m = $.cookie("cookieM");s = $.cookie("cookieSe"); // function begintime(){    var showh = settime(h);    var showm = settime(m);    var shows = settime(s);        var show_span = $(".current-time");        var show_time = showh+":"+showm+":"+shows;        show_span.text(show_time);    s++;    if(s == 60)    {        s = 0;        m++;    }    if(m == 60){        m = 0;        h++;    }    t = setTimeout("starttime()",1000);  //}}function endtime() {    clearTimeout(t);    h = 0;    m = 0;    s = 0;    $.cookie("cookieH", null);    $.cookie("cookieM", null);    $.cookie("cookieSe", null);}

最终的解决方案:

但我去交付任务的时候,我小导师问我:那你把数据存储在本地,那你想过万一他更换设备观看吗?我:。。。。还有这种人!?不过这种情况确实存在。他给出了最终解决方法:还是靠后台啊!!

0 0
原创粉丝点击