Javascript Function setInterval() works only one time

与世无争的帅哥 提交于 2019-12-10 17:18:32

问题


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.



来源:https://stackoverflow.com/questions/27699044/javascript-function-setinterval-works-only-one-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!