[Super detailed~] The three major timers of js: setTimeout, setInterval, requestAnimationFrame

setTimeout (expression, time) => refers to calling the function after a specified time delay, and the number of calls is only once;

setInterval(expression, time) => refers to specifying the expression every specified time, the number of times is not one, such as setting the time to four seconds, performing the operation of blinking every four seconds, and the cycle continues;

Stop timing:

clearTimeout(object) clears the setTimeout object

clearInterval(object) clears the setInterval object

setTimeout

function f(){
    
    
    var out=setTimeout(function(){
    
    
        t.value=i++;
        f();//方法中对自身调用
    },1000);
    if(i>10){
    
    //如果超过10次,则清除 执行,并提示信息
        clearTimeout(out);
        alert("10秒钟已到");
    }
}

setInterval

setInterval(function(){
    
    
  // parseInt解析一个字符串,返回一个整数
  if(parseInt(myDiv.style.width) < 500){
    
    
    myDiv.style.width = parseInt(myDiv.style.width) + 5 + 'px';
    // 总长500,除以5的数字正好是百分比
    myDiv.innerHTML = parseInt(myDiv.style.width)/5 + '%';
  }else{
    
    
    clearInterval(timer);
  }
},16);

requestAnimationFrame

requestAnimationFrame(function fn(){
    
    
  if(parseInt(myDiv.style.width) < 500) {
    
    
    myDiv.style.width = parseInt(myDiv.style.width) + 5 + 'px';
    myDiv.innerHTML = parseInt(myDiv.style.width)/5 + '%';
    // requestAnimationFrame只传入一个参数
    timer = requestAnimationFrame(fn);
  } else {
    
    
    cancelAnimationFrame(timer);
  }
})

Guess you like

Origin blog.csdn.net/m0_58768224/article/details/130036491