通过使用计时器,每隔1秒向服务器发送一条请求,用来自动更新前端的数据
微信小程序端
开启计时器
//开启计时器,注意参数的使用
function startTimer(that) {
timer = setTimeout(function () {
console.log("time:"+time);
time++;
//发送请求
wx.request({
url: 'http://localhost:8080/ranking',
method: 'POST',
header: { 'content-type': 'application/x-www-form-urlencoded' },
data: {
},
success: function (res) {
//打印返回的数据
console.log(res)
var resData = res.data;
if (resData != "") {
that.setData({
time: res.data
})
//获取数据后重新开启定时器发送请求
startTimer(that);
} else {
wx.showToast({
title: '查询失败',
duration: 2000
})
}
}
})
}, 1000);
};
关闭计时器
//停止计时器
function stopTime(){
if(timer != null){
clearTimeout(timer)
}
}
方法调用
start:function(){
startTimer(this)
},
pause:function(){
stopTime()
},
页面显示
<button bindtap="start">开始</button>
<button bindtap="pause">停止</button>
<view style="font-size: 50rpx;text-align: center;">{{time}}</view>
服务器代码(spring)
int num = 1;
@RequestMapping("/ranking")
@ResponseBody
public String ranking(String name, String password) {
System.out.println("排队信息更新,正在加载"+num);
num++;
try {
//延迟5秒,模拟服务器延迟
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return num+"";
}
time.js 代码
// pages/time/time.js
Page({
/**
* 页面的初始数据
*/
data: {
time:"0"
},
start:function(){
startTimer(this)
},
pause:function(){
stopTime()
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function () {
}
})
var time = 1;
var timer;
//开启计时器
function startTimer(that) {
timer = setTimeout(function () {
console.log("time:"+time);
time++;
//发送请求
wx.request({
url: 'http://localhost:8080/ranking',
method: 'POST',
header: { 'content-type': 'application/x-www-form-urlencoded' },
data: {
},
success: function (res) {
console.log(res)
var resData = res.data;
if (resData != "") {
that.setData({
time: res.data
})
//获取数据后重新开启定时器发送请求
startTimer(that);
} else {
wx.showToast({
title: '查询失败',
duration: 2000
})
}
}
})
}, 1000);
};
//停止计时器
function stopTime(){
if(timer != null){
clearTimeout(timer)
}
}
time.wxml 代码
<button bindtap="start">开始</button>
<button bindtap="pause">停止</button>
<view style="font-size: 50rpx;text-align: center;">{{time}}</view>