如果时间太短,setInterval将无法工作

时间:2016-10-24 01:05:28

标签: javascript css setinterval

如果增量小于101ms,我有一个setInterval函数不会执行。时间将超过100毫秒。我希望能够将函数增加10ms。当时间低于101毫秒时,offYstrtPos也会变得不确定。我如何使其工作原理相同,但相反,它增加了10毫秒?



var strtPos;
var offY;
var offX;
var hold = true;
var obj = document.getElementById('obj');

var st = function() {
  offY = obj.offsetTop;
}
var init = setInterval(function() {
  other()
}, 101);  //<-- When I change that value to below 101, it prevents the code from working

var other = function() {
  if (hold) {
    strt();
    hold = false
  };
  console.log(offY)
  console.log(strtPos)
  if (strtPos - 100 <= offY) {
    obj.style.top = (offY - 11) + "px";
  } else {
    clearInterval(init);
    hold = true;
  }
}
var strt = function() {
  strtPos = offY
}
setInterval(st, 100)
&#13;
body {
  margin: 0;
}
#obj {
  width: 50px;
  height: 100px;
  background-color: red;
  position: fixed;
}
&#13;
<div id="obj"></div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

简短的回答是,您需要为offY提供一个最初未定义的值,因此我已经重新安排了代码顶部的变量。

最初,offY仅在约100毫秒(setInterval(st, 100))后获得一个值,并且没有undefined的值other函数的计算赢了& #39;工作。所以你需要首先执行st函数,因此需要一个值&gt; 100。

&#13;
&#13;
var strtPos;
var offX;
var hold = true;
var obj = document.getElementById('obj');
var offY = obj.offsetTop;

var st = function() {
  offY = obj.offsetTop;
}
var init = setInterval(function() {
  other()
}, 10);

var other = function() {
  if (hold) {
    strt();
    hold = false
  };
  console.log(offY)
  console.log(strtPos)
  if (strtPos - 100 <= offY) {
    obj.style.top = (offY - 11) + "px";
  } else {
    clearInterval(init);
    hold = true;
  }
}
var strt = function() {
  strtPos = offY
}
setInterval(st, 100)
&#13;
body {
  margin: 0;
}
#obj {
  width: 50px;
  height: 100px;
  background-color: red;
  position: fixed;
}
&#13;
<div id="obj"></div>
&#13;
&#13;
&#13;