Guys! I wanna ask about Javascript function setInterval(). My problem is that setInterval() works only one time, 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 can't find what is wrong.
When your code calls the function repeatEverySecond it will run setInterval . setInterval will run the function sendMessage every second (1000 ms).
JavaScript setInterval() method. The setInterval() method in JavaScript is used to repeat a specified function at every given time-interval. It evaluates an expression or calls a function at given intervals. This method continues the calling of function until the window is closed or the clearInterval() method is called ...
setInterval() The setInterval() method, offered on the Window and Worker interfaces, repeatedly calls a function or executes a code snippet, with a fixed time delay between each call. This method returns an interval ID which uniquely identifies the interval, so you can remove it later by calling clearInterval() .
Yes, setInterval repeats until you call clearInterval with the interval to stop.
setInterval
expects a callback as first argument, but you are calling the actual function.
Call should be like below
setInterval(function() {
below(t++); }
,1);
So here you are creating an anonymous callback which will call your function below. And better put the exit condition t >= 50
inside below
function
The setInterval
doesn't work even one time. The reason that the function is called once is that you are calling it when trying to use setInterval
, and the return value from the function (which is undefined
) is used in the setInterval
call.
Use a function expression to create an interval that calls below(t++)
. You would put the code that checks the t > 50
condition inside the function, otherwise that will also only run 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 the interval isn't a good idea. As it runs after the page is completed, it will open a new page to write to which replaces the current page.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With