Which way is correct and more efficient in using setInterval() and clearInterval()?

1.

something = setInterval(function() {
    try {
        ...load something
        clearInterval(something);
    } catch (e) {
      // error
    }
}, 5000);

2.

 something = setInterval(function() {
    try {
        ...load something            
    } catch (e) {
      // error
    }
}, 5000);

setTimeout(something, 7000);

EDIT:

For #2, I meant setTimeout() instead of clearInterval().Has been changed.

有帮助吗?

解决方案

I assume the interval you're passing into clearInterval is meant to be something.

Your second example will never fire your timer, because you clear the timer immediately after setting it. You're also passing an argument (7000) into clearInterval that won't get used (clearInterval only accepts one argument).

Your first example is right provided that you want to clear the repeated timer at the point where you're calling clearInterval from within the handler. Presumably that's in an if or similar, because if you want a one-off timed callback you'd use setTimeout, not setInterval.


EDIT:

For #2, I meant setTimeout() instead of clearInterval().Has been changed.

That completely changes the question. No, that's not correct. setInterval schedules the function to be called repeatedly on the interval you give it, you don't pass its return value into setTimeout.

其他提示

If you need something to happen over and over again you use setInterval if you only need it to happen once use setTimeout (you can simulate setInterval by chaining multiple timeouts one after the other). Timeouts only happen once therefore you do no need to clear them. Also clearInterval does not take a time argument so the interval you set will be cleared before it ever executes since classic javascript is synchronous.

just to complete the answer, take many care with setInterval(). if your "...load something" take sometime more time to load than the time according (for a reason or another). it will just don't do it for this time and will wait the next call of setinterval. I encourage to use setTimeout() as much as possible instead.

You can find find below the use cases that are, according to me, aswering to your questions:

For your case 1:

var something = setInterval(function() {
    // Do stuff, and determine whether to stop or not

    if (stopCondition) {
        clearInterval(something);
    }
}, 5000);

For your case 2:

var something = setInterval(function() {
    // Do stuff
}, 5000);

// Pass a function to setTimeout
setTimeout(function() {
    clearInterval(something);
}, 17000);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top