Javascript中的setTimeout,setInterval,requestAnimFrame

这三种方法我们平时初学的时候可能容易混淆,下面我们将使用例子的形式来阐述这三种方法不同的用法。
setTimeout:Calls a function or executes a code snippet after a specified delay.(在特定的时间后执行方法和代码块)
语法:var timeID = setTimeout(func|code,delay)
[javascript] view plain copy 在CODE上查看代码片派生到我的代码片

/*第一种写法 function f(){ console.log("HI"); } setTimeout(f,1000); */ /*第二种写法 setTimeout("console.log('aaa')",2000); */ //第三种写法 setTimeout(function(){console.log("bbb")},2000);
        在2秒之后执行输出操作
      复杂一点例子:

[html] view plain copy 在CODE上查看代码片派生到我的代码片





/*
延迟几秒后调用该方法
*/
var timeoutID;
function delayedAlert(){
timeoutID = window.setTimeout(slowAlert,2000);
}
function slowAlert(){
console.log("That was really show~");
}
function clearAlert(){
window.clearTimeout(timeoutID);
}



Live Example


Show an alert box after two seconds


Cancel alert before it hanppeds


打开页面并打开浏览器控制台,点击”show an alert…” 按钮,就看到我们在2秒后在控制台输出”That was really show~~~” 点击一次2秒后就输出【可以点击多次哦~】
点击“Cancel alert before it happends” 按钮后,就能够取消正在执行的delayedAlert()方法【执行完打印输出后就没作用了~】

     让我们再来看setInterval()方法
     setInterval() : Calls a function or executes a code snippet repeatedly, with a fixed time delay between each call to that function. Returns an intervalID.(在时间间隔内永久重复的执行函数和代码块,返回一个intervalID),下面是一个颜色变幻的例子:

[html] view plain copy 在CODE上查看代码片派生到我的代码片




猜你喜欢

转载自blog.csdn.net/zd717822023/article/details/54708601