admin管理员组

文章数量:1333210

I have this function:

function timedFunction(functionString,timeoutPeriod) {
setTimeout(functionString+"timedFunction(\""+functionString+"\","+timeoutPeriod+");",timeoutPeriod);}

This function me call:

 timedFunction("startStopky();",1000);

startStopky(); is a function that I want in a specified time interval repeatedly run. Everything works excellently, but if I want stop this interval, I have to stop as follows:

for (var i = 1; i < 99999; i++) {
            window.clearInterval(i);
        }

Unfortunately this will stop all intervals, and I want to stop just one particular. How can I do it?

I have this function:

function timedFunction(functionString,timeoutPeriod) {
setTimeout(functionString+"timedFunction(\""+functionString+"\","+timeoutPeriod+");",timeoutPeriod);}

This function me call:

 timedFunction("startStopky();",1000);

startStopky(); is a function that I want in a specified time interval repeatedly run. Everything works excellently, but if I want stop this interval, I have to stop as follows:

for (var i = 1; i < 99999; i++) {
            window.clearInterval(i);
        }

Unfortunately this will stop all intervals, and I want to stop just one particular. How can I do it?

Share Improve this question asked May 6, 2013 at 18:51 user2355775user2355775 331 silver badge3 bronze badges 1
  • 2 Don't pass strings to setTimeout/setInterval. To stop a specific timer, save the timeout/interval ID so that it can be used later to refer to the specific timer. – user2246674 Commented May 6, 2013 at 18:54
Add a ment  | 

4 Answers 4

Reset to default 4

Instead of doing recursive calls to timedFunction just do:

var intervalId = setInterval(startStopky, 1000);

and to clear it just do:

clearInterval(intervalId);

The setTimeout function returns a timeout ID that you use with clearTimeout to remove that timeout. The same goes for intervals but in that case it's a setInterval and clearInterval bo.

E.g.:

var t = setTimeout(yourFunction, 1000);
clearTimeout(t);

var i = setInterval(yourFunction2, 500);
clearInterval(i);

You have a Timeout, but you are clearing an Interval. clearInterval clears intervals, not timeouts.

You want window.clearTimeout(timeoutId)

If you want to stop a single one, you use the processId of that interval.

window.clearTimeout("13");

You really shouldn't be using strings to do this:

function timedFunction(fn, interval) {
  var timerHandle;

  function runIt() {
    fn();
    timerHandle.id = setTimeout(runIt, interval);
  }

  return timerHandle = { id: setTimeout(runIt, interval) };
}

Then you can call it like this:

var handle = timedFunction(startStopky, 1000);

To stop the process:

clearTimeout(handle.id);

本文标签: javascriptHow to stop time interval in my functionStack Overflow