applet timer clear

Scenarios where this problem may occur

The backend of the page request returns no content or the page rolls back after the save is successful (timer delayed return)
Example:

/**
 * 生命周期函数--监听页面加载
 */
onLoad: function (options) {
    
    
	let that = this;
	if (token) {
    
    
	    //发起网络请求
	    wx.request({
    
    
	        url: url,
	        header: {
    
    "Content-Type": "application/x-www-form-urlencoded",},
	        method: "POST",
	        dataType: 'json',
	        data: {
    
    id: id},
	        success(res) {
    
    
		        // 定时器2S后跳转页面
            	setTimeout(function () {
    
    
            		wx.navigateBack({
    
    
                		delta: 1
              		})
            	}, 2000);
	        }
	    })
	}
}

In this case, clicking the return button in the upper left corner will trigger the return event to return to the previous page, but the timer will not end, and the wx.navigateBack event will still be triggered after 2S, that is, the page will jump again.

Solution

  1. There are page hide monitoring (onHide() event) and page unloading monitoring (onUnload() event) in the life cycle of WeChat native
    applet. Timer can be cleared from these two events, but the two events must be distinguished.

Image from WeChat development documentation

code show as below:

Page({
    
    
	data: {
    
    
	    timer:null,
	},
	onLoad: function (options) {
    
    
		let that = this;
		if (token) {
    
    
		    //发起网络请求
		    wx.request({
    
    
		        url: url,
		        header: {
    
    "Content-Type": "application/x-www-form-urlencoded",},
		        method: "POST",
		        dataType: 'json',
		        data: {
    
    id: id},
		        success(res) {
    
    
			        // 定时器2S后跳转页面
			        let timerTem = setTimeout(function () {
    
    
	            		wx.navigateBack({
    
    
	                		delta: 1
	              		})
	            	}, 2000);
			        that.setData({
    
    
				        timer: timerTem
			        })
		        }
		    })
		}
	},
	onUnload: function () {
    
    
		clearInterval(this.data.timer);
    },
    
})
  1. uni-app
    The current version page of uniapp is not hidden, but it is destroyed directly, triggering the unload event, so use onUnload() to destroy the timer in the uniapp framework
data() {
    
    
	id: 1,
	timer: null
},
methods: {
    
    
	getPrice(){
    
    
		const params = {
    
    
			data:{
    
    id:this.id}
		}
		this.$service.post(this.$api.url,params).then((res) => {
    
    
			uni.showToast({
    
    
				title: `${
      
      res.resultMsg}`,
				icon: 'none'
			})
			this.timer = setTimeout(e => {
    
    
				uni.navigateBack()
			}, 2000)
		})
	}
},
onUnload:function(){
    
    
	let that = this;
	if(that.timer) {
    
      
		clearInterval(that.timer);  
		that.timer = null;  
	}
},

Guess you like

Origin blog.csdn.net/chang19951022/article/details/123877033