SOURCE

console 命令行工具 X clear

                    
>
console
let timer = null;
let interval = function (func, wait) {
    let interv = function () {
        if (timer) {
            console.log('有上一个', timer)
            clearTimeout(timer)
            timer = null
        }
        func.call(null);
        timer = setTimeout(interv, wait);
        console.log('开始轮询', timer)
    };
    
    if (timer) {
        console.log('有上一个', timer)
        clearTimeout(timer)
        timer = null
    }
    timer = setTimeout(interv, wait);;
}


let func = function (timer) {
    console.log('请求')
}

let dom = document.getElementsByTagName('button')
dom = document.addEventListener("click", clear)
dom = document.addEventListener("click", start)
function clear() {
    console.log('清除前', timer)
    if (timer) {
        clearTimeout(timer)
        timer = null
        console.log('清除后', timer)
    }
}

function start() {
    interval(func, 2000)
}
<button onclick="clear">停止</button>
<button onclick="start">开始轮询</button>