Skip to content

Instantly share code, notes, and snippets.

@orimdominic
Last active June 4, 2021 12:14
Show Gist options
  • Save orimdominic/02139e47d7d7f915fb537dfc983bb000 to your computer and use it in GitHub Desktop.
Save orimdominic/02139e47d7d7f915fb537dfc983bb000 to your computer and use it in GitHub Desktop.
Implement setInterval method using setTimeout
/*
Implement the setInterval function in such a way that calling SetInterval.prototype.start
will start the function passed to it and run the function at intervals `interval` until
the SetInterval.prototype.clear method is called.
For example:
const theIntervalRunner = SetInterval(()=> console.log("logging'), 1000)
theIntervalRunner.start()
setTimeout(() => theIntervalRunner.clear(), 5000)
will print 'logging' 5 times
function SetInterval(fn, interval) {
}
SetInterval.prototype.start = function () {
}
SetInterval.prototype.clear = function () {
}
*/
// Solution culled from https://michaelzheng.medium.com/implement-setinterval-with-settimeout-bfe1f467731f
// function _setInterval(fn, delay) {
// // wrap the original function, recursively call the wrapper function with setTimeout
// const wrapper = () => {
// fn();
// return setTimeout(wrapper, delay)
// }
// setTimeout(wrapper, delay);
// }
// _setInterval(console.log.bind(null, 'hello world'), 1000);
function SetInterval(fn, interval) {
this.fn = fn;
this.interval = interval;
this.toContinue = true
}
SetInterval.prototype.start = function () {
const wrapper = () => {
if(this.toContinue){
this.fn()
// returning in case the id may be nedded.
// Not really necessary for this particular implementation
return setTimeout(wrapper, this.interval);
}
return
};
wrapper()
}
SetInterval.prototype.clear = function () {
this.toContinue = false
}
const theFn = new SetInterval(() => {console.log("logging")}, 1000)
theFn.start()
setTimeout(() => {
theFn.clear()
}, 5000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment