skip to Main Content

How we can clear the setInterval after the 10 times it print the consoled value.

I have tried a way with simple JS code but I am expecting better answer than what i tried.

my code is given below..

let c = 0;

let datainter = setInterval(() => {
  c += 1;
  console.log(c);
  if(c == 10) {
    inter();
  }
}, 1000)

function inter() {
  clearInterval(datainter);
  console.log('interval ended')
}

2

Answers


  1. An alternative could be setTimeout without clearing anything:

    Array(10).fill().forEach((_,i,arr) => setTimeout(
      () => console.log(i + 1) || i === arr.length - 1 && console.log('ended'), 
      (i + 1) * 1000
    ));
    Login or Signup to reply.
  2. You could use recursion with a call to setTimeout.

    If you want to check if the loop is finished, just wrap it in a promise and call resolve.

    const __loop = (fn, times, timeout, resolve) => {
      if (times <= 0) return resolve();
      fn(); // Call function
      setTimeout(__loop, timeout, fn, times - 1, timeout, resolve);
    };
      
    const repeat = (fn, times = 1, timeout = 1000) =>
      new Promise((resolve, reject) => __loop(fn, times, timeout, resolve));
    
    let i = 0;
    repeat(() => {
      console.log(i++);
    }, 5)
      .then(() => console.log('Interval ended...'));

    Alternatively, you could create options and have a callback:

    const defaultOptions = {
      count: 1,
      onStop: undefined,
      timeout: 1000
    };
    
    const __loop = (fn, options) => {
      if (options.count <= 0) return options.onStop();
      fn(); // Call function
      const count = options.count - 1;
      setTimeout(__loop, options.timeout, fn, { ...options, count });
    };
      
    const repeat = (fn, options = defaultOptions) =>
      __loop(fn, { ...defaultOptions, ...options });
    
    let i = 0;
    repeat(() => {
      console.log(i++);
    }, {
      count: 5,
      onStop: () => console.log('Interval ended...')
    });
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search