Adding TimingFunctions/IntervalTimer#237
Conversation
|
@nandanvasudevan thanks for contributing, Please read Contribution Guidelines and run |
|
This is all kinds of wrong. Your class isn't a singleton because a = new IntervalTimer()
b = new IntervalTimer()
console.log(a === b) // falseA way to make a singleton that is close to what you wrote would be class IntervalTimer {
constructor() {
if(IntervalTimer.instance)
return IntervalTimer.instance
// ... rest of constructor here
}
}Also, there is no reason to make it a singleton since JS supports very well having multiple
You don't actually measure time elapsed: startTimer () {
this.timer = setInterval(this.callBack, this.interval)
}
/**
* @return {number} Elapsed time since start.
*/
getRunTime () {
return this.timer
}On a more conceptual level, The best pure-JS interval will always have to be blocking (in which case making it a singleton makes sense), but that's only useable in a threaded context (like a web worker or worker thread) because it blocks the execution of anything else. class BlockingInterval {
constructor(
callback = () => {},
interval = 0
) {
if(BlockingInterval.instance)
return BlockingInterval.instance
this.callback = callback
this.interval = interval
this.click(this.interval)
}
click(interval, start = performance.now()) {
while(performance.now() - start < interval){}
this.callback()
this.click(interval, start + interval)
}
}
let last = performance.now()
const a = new BlockingInterval(() => {
const current = performance.now()
console.log(current - last)
last = current
}, 500)If you need an interval for drawing in the browser, use the same principle but with class FrameInterval {
constructor(
callback = () => {},
interval = 0
) {
this.callback = callback
this.click(interval)
}
async click(interval, start = performance.now()) {
while(performance.now() - start < interval){
await new Promise(requestAnimationFrame)
}
this.callback()
this.click(interval, start + interval)
}
}
let last = performance.now()
const a = new FrameInterval(() => {
const current = performance.now()
console.log(current - last)
last = current
}, 500)If you are more concerned w/ the average interval being correct, you should use a class DriftCompensatedInterval {
constructor(
callback = () => {},
interval = 0
) {
this.callback = callback
this.interval = interval
this.click()
}
click(drift = 0) {
const start = performance.now()
setTimeout(() => {
this.callback()
this.click((performance.now() - start) - this.interval)
}, this.interval - drift)
}
}
let last = performance.now()
const a = new DriftCompensatedInterval(() => {
const current = performance.now()
console.log(current - last)
last = current
}, 500) |
|
I didn't know about any of these. Thanks for pointing it out. |
Welcome to JavaScript community
Describe your change:
Checklist:
Example:
UserProfile.jsis allowed butuserprofile.js,Userprofile.js,user-Profile.js,userProfile.jsare notFixes: #{$ISSUE_NO}.