实现携程X分钟前有人预定功能
原理:利用cookie与计时器两部分;
首先,进入页面,x会被随机数赋值,赋值后x会一分钟加1,直到加到60,再从1开始累加。
页面是否相同是根据页面的url后的id值判断;
<span id='myspan'></span> x分钟前有人预定该景点
<script>
$(document).ready(function() {
if (window.location.href.includes('?')) {
if (window.location.href.split('?')[1].split('=')[0] === 'id') {
var ids = window.location.href.split('?')[1].split('=')[1];
var date = new Date();
date.setTime(date.getTime() + ( 600*1000));
//console.log(decodeURI(ids));
//console.log($.cookie('cookie_urlId'));
urlId = decodeURI(ids); //url的id值
if ($.cookie('cookie_urlId') === urlId) {
console.log(true);
//随机数代码
if ($.cookie('redomnum' + urlId) === undefined) {
//console.log($.cookie('redomnum'));
var num = parseInt(60*Math.random());
if (num === 0) {
num = 1;
}
$('#myspan').text(num);
$.cookie('redomnum' + urlId, num, { express: date });
} else {
$('#myspan').text($.cookie('redomnum' + urlId));
};
} else {
$.cookie('cookie_urlId', urlId, { express: date });
//随机数代码
if ($.cookie('redomnum' + urlId) === undefined) {
//console.log($.cookie('redomnum'));
var num = parseInt(60*Math.random());
if (num === 0) {
num = 1;
}
$('#myspan').text(num);
$.cookie('redomnum' + urlId, num, { express: date });
} else {
$('#myspan').text($.cookie('redomnum' + urlId));
}
}
sendMessage();
function sendMessage(){
window.setInterval(SetReminTime,1000 * 60);
}
function SetReminTime(){
var num = $.cookie('redomnum' + urlId);
if(num === '60'){
num = 0;
}
$.cookie('redomnum' + urlId, ++num, { express: date });
$('#myspan').text($.cookie('redomnum' + urlId));
}
}
}
});
</script>