javascript - Why clearInterval doesn't work on a function - Stack Overflow

this is the codevar t = ()=>{setInterval(()=>{console.log('hello')},1000)}t();clearInte

this is the code

var t = ()=>{

    setInterval(()=>{

        console.log('hello')

    },1000)


}

t();

clearInterval(t)

Why the clearinterval does not block execution of the setInterval?

this is the code

var t = ()=>{

    setInterval(()=>{

        console.log('hello')

    },1000)


}

t();

clearInterval(t)

Why the clearinterval does not block execution of the setInterval?

Share Improve this question asked Jul 21, 2017 at 14:25 MarkMark 6910 bronze badges 0
Add a ment  | 

5 Answers 5

Reset to default 5

It doesn't work on a function because that's just now how the mechanism was designed. Calls to setInterval() return a number that acts as an identifier for the timer that the call establishes. That number is what has to be passed to clearInterval().

It doesn't cause an error to pass something that's not a number, or to pass a number that doesn't identify an active timer, but the call has no effect.

In your case, your t() function could simply return the result of the setInterval() call, and your outer code can save that for use later however you like.

It's because you need to return the id of the interval and clear that id.

According to the documentation:

setInterval returns an interval ID which uniquely identifies the interval, so you can remove it later by calling clearInterval().

//function that keeps logging 'hello' on the console
var t = ()=>{
    //return the id of the interval
    return setInterval(()=>{
        console.log('hello')
    },1000)

}

//get the id of the interval created by the "t" function
var id = t();
//alerts the id just to see it
alert(id);
//clear it - function will stop executing
clearInterval(id);

References

https://developer.mozilla/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval

because you should clearInterval on reference for setInterval().

var interval = setInterval();
clearInterval(interval); 

T is not equal to the setInterval returned value as you don't return a value from your arrow function, and don't assign it to a value.

Try this snippet instead:

var t = ()=>
    setInterval(()=>{
        console.log('hello')
    },1000)

var interval = t();
clearInterval(interval);
let intervalId = null;

cycle(true);

function cycle(r) {

    let myInterval = () => {

        return setInterval(() => plusSlides(1), 1000);
    }

    if (!r) {
        clearInterval(intervalId);
      
    } else {
        intervalId = myInterval();
        
    }
}

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1743919338a4529764.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信