ClearInterval not clearing setInterval after 10 seconds

62 Views Asked by At

*** EDIT *** I have tried this..

StartPollingServer: () => {
    return setInterval(() => {
    MyTest.PollingServer();
    }, 1000);
}

and also have tried

StartPollingServer: () => {
    const a = 
    setInterval(() => {
    MyTest.PollingServer();
    }, 1000);
    return a;
},

and still the variable test comes back empty

I am unsure why the clearInterval isn't clearing the setInterval after running for 10 seconds, can someone point out why the clearInterval isn't working

var MyTest = MyTest || {};
MyTest = {
  StartPollingServer: () => {
    setInterval(() => {
      MyTest.PollingServer();
    }, 1000);
  },
  PollingServer: () => {
    console.log("Polling Server");
  },
  StopPollingServer: (f) => {
    clearInterval(f);
    f = null;
  }
}

var test = MyTest.StartPollingServer();

setTimeout(() => {
  MyTest.StopPollingServer(test);
}, 10000);

1

There are 1 best solutions below

3
Some random IT boy On

Your f is not the correct interval handle.

You need to store the result of setInterval into some property and then use that into the clearInterval.

let f = null
const obj = {
  op1: () => {
    f = setInterval(...)
    // More instructions
  },
  op2: () => { 
    clearInterval(f)
    // More instructions
  }
}

In my example I used a variable outside the object but you may use this and function to be able to reference the f property within your object