簡單定時器:
前幾天給頁面增加了一個簡單的定時功能,但是由於用的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);
}
最終的解決方案:
但我去交付任務的時候,我小導師問我:那你把數據存儲在本地,那你想過萬一他更換設備觀看嗎?我:。。。。還有這種人!?不過這種情況確實存在。他給出了最終解決方法:還是靠後臺啊!!