1.setTimeout方式
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<script src="./dingshiqi.js"></script>
<body>
<h1>定时</h1>
</body>
</html>
console.log("来了");
let timerId; // 声明一个变量用于存储定时器的ID
startTimer();//开始定时器
//设置一个3分钟的定时器
function startTimer() {
console.log("设置定时器");
const intervalTimeInMilliseconds = 1 * 60 * 1000; // 1分钟的毫秒数
timerId = setTimeout(function () {
sendRequest(); // 执行请求函数
startTimer(); // 继续设置定时器,实现周期性执行
}, intervalTimeInMilliseconds);
}
function sendRequest() {
console.log('1分钟发送请求测试');
}
一分钟后会进入sendRequest()
2.setInterval方式(推荐)
var autoSaveFlag = false;
var autoSaveUrl = "/xxxxxxxxx/autoSave";
if(currentStoryId == 0){
autoSaveFlag = true;
}
/*************自动暂存 ***********/
function autoSaveReady() {
if ((currentStory&¤tStory.statusName == "草稿")){
autoSaveFlag=true;
}
if(autoSaveFlag){
// 检测标题和正文同时不为空时自动暂存
var _wbtitle = $("#title").val();
var content = ueditor.getContent();
if(content != undefined && content != null && content.length > 0 && _wbtitle.trim().length >0){
$.post(autoSaveUrl, {"storyId":currentStoryId, "title":_wbtitle, "content":content, "type": isPaperStory==0?"":"paperStory"}, function (data) {
if(data){
currentStoryId = data;
currentStory.id = data;
layer.msg('自动暂存成功',{time: 2000});
}
}, "json");
}
}
}
setInterval('autoSaveReady()', 0.5 * 60 * 1000);//轮询执行,5分钟一次 测试时设为0.5