我想循环从 3 数到 0,然后再倒数到 3。这是一种"滑块"实现。一切都运行良好,直到从counterry
到达clearInterval
。我错过了什么?
var counttx = 0, // counter
counterrx = setInterval(timerrx, 1000), // countup - start
counterry; // countdown after reach 3
function timerrx(){
counttx = counttx+1;
//console.log(counttx);
if(counttx > 2){
counterry = setInterval(timerry, 1000);
clearInterval(counterrx);
}
}
function timerry(){
counttx = counttx-1;
//console.log(counttx);
if(counttx < 2){
setInterval(timerrx, 1000);
clearInterval(counterry);
}
}
使用单个循环:
let counttx = 0, countup = true;
const counter = document.getElementById('counter');
function timerr()
{
if (countup)
{
++counttx;
if (counttx >= 3)
countup = false;
}
else
{
--counttx;
if (counttx <= 0)
countup = true;
}
counter.value = counttx;
}
setInterval(timerr, 1000);
<input type="number" id="counter" value="0" />
代码
let i = 0;
setInterval(() => {
console.log(Math.abs(i++%6 - 3))
}, 1000);
解构
-
i++
→i
在每次报价时无限增加一个 -
%6
→最大 v值的两倍模数(除法剩余 ex.10 % 6 = 4
) -
- 3
→删除范围(因此数字将始终在 3 到 -3 之间,否则它将介于 0 和 6 之间) -
Math.abs()
→删除 - (确保数字从 0 移动到 3 并移回)
步骤可视化
i++
∞ .
.
.
/
/
/
/
0
i++%6
6
/ / / .
/ / / .
/ / / .
/ / / /
/ / / /
0
i++%6-3
3
/ /
/ /
0 / / .
/ / .
/ / .
-3
Math.abs(i++%6-3)
3
/ /.
/ / .
/ / .
0
8 个第一次迭代的示例输出:
i
0-
0%6
0 -
0-3
-3 -
Math.abs(-3)
3
-
i
1-
1%6
1 -
1-3
-2 -
Math.abs(-2)
2
-
i
2-
2%6
2 -
2-3
-1 -
Math.abs(-1)
1
-
i
3-
3%6
3 -
3-3
0 -
Math.abs(0)
0
-
i
4-
4%6
4 -
4-3
1 -
Math.abs(1)
1
-
i
5-
5%6
5 -
5-3
2 -
Math.abs(2)
2
-
i
6-
6%6
0 -
0-3
-3 -
Math.abs(-3)
3
-
i
7-
7%6
1 -
1-3
-2 -
Math.abs(-2)
2
-
实现示例
const max = 10
let i = max;
const $body = document.querySelector('body');
setInterval(() => {
const val = Math.abs(i++%(max * 2) - max);
const $el = document.createElement('i');
$el.style = `--i: ${i}; --val: ${val}`;
$body.appendChild($el);
window.scrollTo(window.innerWidth, 0);
console.log(val);
}, 200);
i {
--i: 0;
--val: 0;
--size: 10px;
position: absolute;
background: black;
width: var(--size);
height: var(--size);
top: var(--size);
left: calc(-10 * var(--size));
transform: translate(
calc(var(--i) * var(--size)),
calc(var(--val) * var(--size))
)
}
替代方法
Math.acos(Math.cos(i * Math.PI)) / Math.PI;
或
Math.abs(i - Math.floor(i) - .5);
其中i
是0
- Infinity
之间的float
。结果也是一个float
,需要乘以您的最大值和四舍五入(目标值)。
基本逻辑可能如下所示,您可以针对 javascript 中的间隔计时器进行调整。
int counter=0;
int delta=1;
bool finished=false;
while(!finished)
{
counter+=delta;
if(counter==3)
{
delta=-1;
}
if(counter==0)
{
delta=1;
}
if(condition to end loop is met)
{
finished=true;
}
}