简体   繁体   English

Javascript函数setInterval()只能运行一次

[英]Javascript Function setInterval() works only one time

Guys! 伙计们! I wanna ask about Javascript function setInterval(). 我想问一下Javascript函数setInterval()。 My problem is that setInterval() works only one time, not repeating. 我的问题是setInterval()只工作一次,而不是重复。

Here is my HTML Code 这是我的HTML代码

<button id = 'btun' name = 'btun' onclick = 'changecolor();' class = 'btn btn-success btn-block'>Color Change</button>

and Javascript Code 和Javascript代码

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. 我找不到有什么不对。

The setInterval doesn't work even one time. setInterval甚至不能工作一次。 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. 函数调用一次的原因是您在尝试使用setInterval时调用它,并且在setInterval调用中使用函数的返回值( undefined )。

Use a function expression to create an interval that calls below(t++) . 使用函数表达式创建一个调用below(t++)的区间。 You would put the code that checks the t > 50 condition inside the function, otherwise that will also only run once. 您可以将检查t > 50条件的代码放在函数内部,否则它也只运行一次。

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. 注意:在间隔中使用document.write不是一个好主意。 As it runs after the page is completed, it will open a new page to write to which replaces the current page. 在页面完成后运行时,它将打开一个要写入的新页面来替换当前页面。

setInterval expects a callback as first argument, but you are calling the actual function. setInterval期望将回调作为第一个参数,但是您正在调用实际函数。

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 并且最好将退出条件t >= 50置于函数below

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM