-->

Javascript Function setInterval() works only one t

2019-06-26 07:42发布

问题:

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.

回答1:

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



回答2:

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.