Sylvia
Sylvia

Reputation: 277

How to make clearInterval work?

I can not figure out why clearInterval doesn't work below, Could anyone tell me what's the matter with my coding?

Thank you very much!

function timehandle(){
alert("Take a break")
}

setInterval(timehandle, 5000);
var getout=setInterval(timehandle, 5000);
var button=document.getElementById("button");
button.onclick=clearInterval(getout);

Upvotes: 1

Views: 43

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386654

You need a single interval and a function which calls clearInterval, because without, it clears the interval directly by assinging the return value of clearInterval.

BTW, it is usefull to use a different id of the tag, because some user agents use the id as variable name and it could be leading to conflicts by using own same named variables.

function timehandle() {
    console.log("Take a break");
}

var getout = setInterval(timehandle, 5000);
var button = document.getElementById("btn");
button.onclick = function () { clearInterval(getout); };
<button id="btn">clear</button>

Upvotes: 4

Related Questions