手写js中setTimerOut功能
用原生setTimerOut和手写setTimerOut进行比较,可以让同学们更加深刻理解js
原生setTimerOut
setTimeout(function (a, b) {
console.log('我执行了');
console.log('参数a', a);
console.log(b);
}, 2000, 'dddd', 123);
手写setTimerOut
// 1:求当前时间的时间戳
var now = new Date().getTime();
// 2:求未来时间的时间戳
function setTimeZA(callback, time,a) {
// 获取计时器执行时间。
var now = new Date().getTime();
// 求 回调函数 将来在什么时间执行
var out = now + time;
// 如何实时监听时间的变化
var timer = setInterval(function () {
var timeout = new Date().getTime();
// 用监听的时间,与 程序将来执行的时间进行比较。
if (timeout >= out) {
clearInterval(timer)
// 当时间到了2000后,让 callback执行
callback(a);
}
}, 0)
}
setTimeZA(function (a) {
console.log('=================================');
console.log('zhangao');
console.log(a);
}, 500,'dfsadf')