const counter = (start, end) => { let timeout = null if (start <= end) { console.log(start) start++ timeout = setTimeout(() => counter(start, end), 100) } return { cancel: () => {clearTimeout(timeout)} } } counter(1,10) counter(1,10).cancel()