考虑到页面刷新需要记录首次访问页面的时间 不然每次刷新都会重新计时 导致一直不能调用接口
var interval = 60000; // 轮询间隔为1分钟
var notificationSound = document.getElementById("notificationSound");
var isPlaying = false;
// 消息通知 记录开始时间
var startTime = localStorage.getItem('startTime');
// 如果没有存储开始时间,则将当前时间存储到本地存储中
if (!startTime) {
startTime = Date.now();
localStorage.setItem('startTime', startTime);
}
// 每隔60秒调用一次消息接口
//setInterval(callMessageAPI, interval);
// 计算距离上次页面加载开始的时间
var elapsedTime = Date.now() - startTime;
// 然后计算下一次调用消息接口的时间
var nextCallTime = interval - (elapsedTime % interval);
// 在下一次调用消息接口的时间后调用callMessageAPI函数
setTimeout(function() {
callMessageAPI();
// 设置定时器,在接下来的每隔60秒后再次调用callMessageAPI函数
setInterval(callMessageAPI, interval);
}, nextCallTime);
// 定义函数来调用消息接口
function callMessageAPI() {
// 这里调用你的消息接口
if($('#topBaseId').val()!==undefined){
$.post('/talk/unread',{baseId:$('#topBaseId').val()},function (res){
playNotificationSound();
$("#unread").removeClass('hide-im').text(parseInt(res));
})
}
}
// 播放通知音乐
function playNotificationSound() {
// 检查是否正在播放音乐
if (!isPlaying) {
// 播放音乐
notificationSound.play();
isPlaying = true;
// 在3秒后停止音乐
setTimeout(function() {
notificationSound.pause();
notificationSound.currentTime = 0; // 重置音乐播放位置
isPlaying = false;
}, 1000);
}
}