Javascript 倒计时和倒计时循环
我想在一个循环中从3数到0,然后再回到3。这是一种“滑块”实现。在从Javascript 倒计时和倒计时循环,javascript,setinterval,Javascript,Setinterval,我想在一个循环中从3数到0,然后再回到3。这是一种“滑块”实现。在从计数器到达清除间隔之前,一切正常运行。我错过了什么 var counttx = 0, // counter counterrx = setInterval(timerrx, 1000), // countup - start counterry; // countdown after reach 3 function timerrx(){ counttx = counttx+1; //conso
计数器
到达清除间隔
之前,一切正常运行。我错过了什么
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);
}
}
var counttx=0,//计数器
计数器Rx=设置间隔(timerrx,1000),//倒计时-启动
柜台;//到达3后倒计时
函数timerrx(){
counttx=counttx+1;
//console.log(counttx);
如果(counttx>2){
countery=设置间隔(timerry,1000);
清除间隔(计数器Rx);
}
}
函数timerry(){
counttx=counttx-1;
//console.log(counttx);
如果(counttx<2){
设置间隔(timerrx,1000);
净空间隔(计数器);
}
}
使用单个循环:
让counttx=0,countup=true;
常量计数器=document.getElementById('counter');
函数timerr()
{
如果(倒计时)
{
++counttx;
如果(counttx>=3)
倒计时=假;
}
其他的
{
--counttx;
if(counttx基本逻辑可以如下所示,您可以针对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;
}
}
代码
设i=0;
设置间隔(()=>{
log(Math.abs(i++%6-3))
}, 1000);
解构
i++
→ <代码>i
会无限期地在每个刻度上增加一个
%6
→ 最大V值的两倍模(除法剩余值,例如10%6=4
)-3
→ 删除范围(因此数字将始终在3和-3之间,否则将在0和6之间)Math.abs()
→ 删除-(确保数字从0移到3再移回来)∞ .
.
.
/
/
/
/
0
i++%6
6
/ / / .
/ / / .
/ / / .
/ / / /
/ / / /
0
i++%6-3
3
\ /\ /\
\ / \ / \
0 \ / \ / .
\ / \ / .
\/ \/ .
-3
3
\ /\ /.
\ / \ / .
\/ \/ .
0
Math.abs(i++%6-3)
第8次迭代的输出示例:
i
0
0%6
00-3
-3Math.abs(-3)
3i
1
1%6
11-3
-2Math.abs(-2)
2i
2
2%6
22-3
-1Math.abs(-1)
1i
3
3%6
33-3
0Math.abs(0)
0i
4
4%6
44-3
1Math.abs(1)
1i
5
5%6
55-3
2Math.abs(2)
2i
6
6%6
00-3
-3Math.abs(-3)
3i
7
7%6
11-3
-2Math.abs(-2)
2const max=10
设i=max;
const$body=document.querySelector('body');
设置间隔(()=>{
const val=Math.abs(i++%(max*2)-max);
const$el=document.createElement('i');
$el.style=`--i:${i};--val:${val}`;
$body.appendChild($el);
scrollTo(window.innerWidth,0);
控制台日志(val);
},200);
i{
--i:0;
--val:0;
--尺寸:10px;
位置:绝对位置;
背景:黑色;
宽度:var(--大小);
高度:var(--大小);
顶部:var(--大小);
左:计算(-10*var(-size));
转换:翻译(
计算(var(--i)*var(--size)),
计算(var(--val)*var(--size))
)
}
试着为你的答案添加一个小的描述。@Martínca尽了最大努力,希望它能帮助你回答你的问题吗?