Try to search your question here, if you can't find : Ask Any Question Now ?

Why clearInterval is not working in my script?

HomeCategory: stackoverflowWhy clearInterval is not working in my script?
kundan asked 1 week ago

I have got a problem with my clearInterval method.
I learn about JS in depth at FrontendMasters and there is an exercise where you need to use setInterval and log a string at every second and then run clearInterval after 5 seconds. I have access to the right solution but I would like to know why my solution is not working to get better understanding. The console.log('clear called', func); runs after 5 seconds and log the clear called string and the function body. I have tried to use setTimeout to wrap wrapper.stop() but it did not work that way either. I have used closures to try to solve the exercise. Here is my script.

function sayHowdy() {
 console.log('Howdy');
}


function everyXsecsForYsecs(func, interval, totalTime) {
 function clear() {
   console.log('clear called', func);
   clearInterval(func);
 }
 return {
   start() {
     setInterval(func, interval);
   },
   stop() {
     setTimeout(clear, totalTime);
   }
 }
}


const wrapper = everyXsecsForYsecs(sayHowdy, 1000, 5000);
wrapper.start();
wrapper.stop();

Thanks

1 Answers
Best Answer
Arben answered 1 week ago
Your Answer

6 + 10 =

Popular Tags

WP Facebook Auto Publish Powered By : XYZScripts.com