1. 程式人生 > >js精準時間叠代器(定時器)

js精準時間叠代器(定時器)

tof fse 器) val 時間 ext start clas local

window.setMyInterval = function(func, interval){
    var nexttime    = interval;
    var start        = new Date().getTime();
    var now            = null;
    var toffset        = 0;
    
    var i            = 0;

    var gogogo = function(){
        window.setTimeout(function(){
            i++;
            now            
= new Date().getTime(); toffset = now - (start + i * interval); nexttime = interval - toffset; func(); gogogo(); }, nexttime); }; gogogo(); }

使用示例:

window.setMyInterval(function(){
    console.log(new Date().toLocaleString());
}, 
2000);

js精準時間叠代器(定時器)