Skip to content

Instantly share code, notes, and snippets.

@zyf0330
Last active April 19, 2017 10:38
Show Gist options
  • Save zyf0330/13a2821ced1f3141f9bdee34e24864c4 to your computer and use it in GitHub Desktop.
Save zyf0330/13a2821ced1f3141f9bdee34e24864c4 to your computer and use it in GitHub Desktop.
To test actual effect of JS timer to show they are not accurate
'use strict';
/**
* Created by zyf on 17-4-19.
*/
let i;
let times = 10,
delay = 100;
let startTime, lastTime, now, durations;
const workNum = 100000;
let workResult = [];
const init = (_times, _delay, _work, _endWork) => {
i = 0;
durations = [];
workResult = [];
lastTime = startTime = Date.now();
_times > 0 && (times = _times);
_delay > 0 && (delay = _delay);
_work && (work = _work);
_endWork && (endWork = _endWork)
};
let work = (timer) => {
// waste time
for (let i = 0; i < workNum; i++) {
workResult.push(i)
}
};
let endWork = () => {
for (let i = 0; i < workResult.length; i++) {
if (i == 0) {
continue
}
let num = workResult[i];
if (num === 0) {
num = workNum;
}
if (num - 1 != workResult[i - 1]) {
return console.error('bad workResult')
}
}
console.log('good workResult')
};
const handle = (which, timer, next) => {
now = Date.now();
durations.push(now - lastTime);
lastTime = now;
i++;
if (i === times) {
which === 'interval' && clearInterval(timer);
which === 'timeout' && clearTimeout(timer);
console.log(which);
const pastTime = now - startTime;
console.log('workTimes', times, 'real times', durations.length);
const expectTime = times * delay;
console.log(
'expect time', expectTime,
'real pastTime', pastTime,
'over percent', ((pastTime - expectTime) / expectTime * 100).toFixed(3) + ' %'
);
console.log(
'expect duration', delay,
'real average duration', (pastTime / times).toFixed(3)
);
endWork();
next && setTimeout(next, 0);
}
};
const timeoutDo = (next) => {
const _do = (timer) => {
work(timer);
timer = setTimeout(() => {
_do(timer)
}, delay);
handle('timeout', timer, next);
};
let timer = setTimeout(() => {
_do(timer)
}, delay);
return timer
};
const intervalDo = (next) => {
const timer = setInterval(() => {
work(timer);
handle('interval', timer, next);
}, delay);
return timer
};
module.exports = {
init: init,
timeoutDo: timeoutDo,
intervalDo: intervalDo
};
// init(100, 100)
// timeoutDo()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment