Javascript setInterval () function only works once
Guys! I want to ask about the Javascript setInterval () function. My problem is that setInterval () only works once, not repeating.
Here is my HTML code
<button id = 'btun' name = 'btun' onclick = 'changecolor();' class = 'btn btn-success btn-block'>Color Change</button>
and Javascript Code
function below(t){
var button = document.getElementById('btun');
var quadrant = (t*t + 2*t + 1)+"px";
console.log('ye');
button.style.marginTop = quadrant;
document.write(pix);
}
var doBelow = setInterval(below(t++),1);
if(t > 50){
clearInterval(doBelow);
}
I cannot find what is wrong.
source to share
setInterval
expects a callback as the first argument, but you are calling the actual function.
The call should look like this
setInterval(function() {
below(t++); }
,1);
So here you are creating an anonymous callback that will call your below function. And it's better to put an exit condition t >= 50
inside below
function
source to share
setInterval
works more than once. The reason a function is called once is because you call it when you try to use it setInterval
, and the return value from the function (which undefined
) is used in the call setInterval
.
Use a function expression to create an interval that calls below(t++)
. You have to put the code that checks the condition t > 50
inside the function, otherwise it will only be executed once.
function below(t){
var button = document.getElementById('btun');
var quadrant = (t*t + 2*t + 1)+"px";
console.log('ye');
button.style.marginTop = quadrant;
document.write(pix);
if(t >= 50){
clearInterval(doBelow);
}
}
var doBelow = setInterval(function() { below(t++); },1);
Note. Using document.write
in an interval is not a good idea. When it is run after the page has finished, it will open a new write page, replacing the current page.
source to share