Origin of the matter

In the process of doing the project, I met such a requirement: press the button lightly, the event will be triggered once, and press the button long, the event will be triggered continuously. Wechat does not provide this method, which needs to be completed by the developers themselves.

Logical analysis

When the button is pressed, the pressed time stamp and the state of a button will be obtained and written into this.data. After the writing is successful, a recursive function will be started. Is a click event. When the button is released, change the button state and clear the timer.

Code implementation

touchStart: function(e){
    let timeStart = this.getTime();
    let isTouch = true;
    this.setData({timeStart, isTouch}, this.getNum)
}

touchEnd: function(){
    this.setData({ isTouch: false }, this.getNum)
}

getNum: function() {let { timeStart, isTouch } = this.data;
    let timeNow = this.getTime();
    let timeNum = 200;
    let num = timeNow - timeStart;
    let touchType = num < timeNum ? 'click': 'long press';
    if(isTouch){// FNC does what it wants to do this.timer =setTimeout(this.getNum, 100)
    }
    else{
        clearTimeout(this.timer)
    }
}

getTime: function() {let time = new Date()
    returnTime.gettime ()} // Get the number of milliseconds for the current timeCopy the code

Wechat tips

SetData ({}, cb) this. SetData ({}, cb) is a callback function

BUG fixes

Although according to the above situation can achieve the desired effect, but still not perfect, through the measured, when rapid click and loosen (within 100 ms), don’t think that will perform the function of trigger, in order to be compatible with this kind of situation, I made a little change, added a bindtap function, and in a state to determine whether to add a trigger to perform the function

/ / tap bindtap function:function() {let { isSend } = this.data
    if(! IsSend){// FNC execute function}} //getNum make adaptive change getNum:function() {let { timeStart, isTouch, isSend } = this.data;
    let timeNow = this.getTime();
    let timeNum = 200;
    let num = timeNow - timeStart;
    let touchType = num < timeNum ? 'click': 'long press';
    if(isTouch){// FNC does what it wants to do this.setData({isSend:true}) // Add the code this.timer =setTimeout(this.getNum, 100)
    }
    else{
        clearTimeout(this.timer)
        this.setData({ isSend:false}) // Added code}} //Copy the code

Since the level is limited, we can only modify it in this way. If there is a better way, we welcome your comments and suggestions