Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
540 views
in Technique[技术] by (71.8m points)

js 如何判断数据流连续几秒内没有变化

我有一个websocket连接,连续不间断接收消息的,如何判断消息三秒内没有变化?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

构建一个缓冲类,定义一个push方法,可以存入数据,同时打上时间戳,定时清除超时数据.
定义一个check方法,调用时检查缓存的数据是否一致.

class Stack{

    clear() {
        const now = Date.now()
        this.pool = this.pool.filter(it => now - it.timestamp < this.MAX_TIME_GAP)
    }
    
    push(data) {
        this.pool.push({
            data,
            timestamp: Date.now()
        })
    }
    
    check(isSame = ((a,b)=> a===b)) {
        this.clear();
        return this.pool.every(a => isSmame(a.data, this.pool[0].data))
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...