setTimeout 模拟 setInterval

var timer;
    window.onload = function(){
        setT();
        document.getElementById('btn').addEventListener('click',function(e){
           clearInterval(timer);
           console.log(timer,"c");
        });
    };

    function setT(){
        timer = setTimeout(function () {
            setT();
            console.log(timer,"timer");
        },3000)
    }
setTimeout 模拟的setInterval 可以通过全局变量接受 然后 通过clearInterval清除定时器。
解释:setInterval不会清除定时器队列,每重复执行1次都会导致定时器叠加,最终卡死你的网页。
但是setTimeout是自带清除定时器的
原文地址:https://www.cnblogs.com/tutao1995/p/11820828.html