[Web 前端] 024 js 的定时器及函数

1. Javascript 定时器

1.1 计时事件

  • 设定一个间隔,时间到了后准时执行代码,此为“计时事件”

1.2 作用

1、制作动画

2、异步操作

1.3 定时器的类型及语法

  • setInterval() 和 setTimeout() 是 Window 对象的两个方法
/*
定时器:
setTimeout 单次的定时器
clearTimeout 关闭单次的定时器 setInterval 多次的定时器
clearInterval 关闭多次的定时器
*/ function timeGoesBy(){
console.log("Time flies by.");
} var time1 = setTimeout(timeGoesBy, 5000);
var time2 = setInterval(timeGoesBy, 500); setTimeout(function(){
clearTimeout(time1);
console.log("time1 has no chance to carry it out."); clearInterval(time2);
console.log("time2 was executed 6 times.");
}, 3000);
  • 运行结果
⑥ Time flies by.
time1 has no chance to carry it out.
time2 was executed 6 times.

2. Javascript 函数

2.1 使用 function 语句定义函数

function abc(){
alert('abc');
}

2.2 在表达式中定义函数

/*
形式
var 函数名 = function(参数1, 参数2, ...){函数体};
*/ var add = function(a, b){
return a+b;
} // 调用函数
document.write(add(50, 20));

2.3 arguments

  • 在函数代码中,使用特殊对象 arguments,开发者无需明确指出参数名,就能访问它们

  • 例如,在函数 sayHi() 中,第一个参数是 message,用 arguments[0] 也可以访问这个值

  • 即,第一个参数位于位置 0,第二个参数位于位置 1,依此类推

  • 举例

/* 1. 使用 function 关键字定义函数
此法优先级较高,不限调用地点
JS 中没有默认值参数 小发现:把 console.log() 写成 print() 会调出打印机
*/
function demo(a, b){
console.log('a =', a, '\tb =', b)
console.log(arguments);
for(i in arguments){
// console.log('i =', i, '\targuments[' + i + '] =', arguments[i]);
console.log('i = %s\targuments[%s] = %d', i, i, arguments[i]);
}
console.log("函数被调用了!");
}
// demo(1, 2);
// demo(); // 少传参数 -> undefined
demo(1, 2, 3); // 多传参数 -> 多余的参数会被忽略
};
  • 运行结果
a = 1 	b = 2
Arguments(3)
i = 0 arguments[0] = 1
i = 1 arguments[1] = 2
i = 2 arguments[2] = 3
函数被调用了!

2.4 关于变量和参数问题:

  • 函数外面定义的变量是全局变量,函数内可以直接使用

  • 在函数内部没有使用 var 定义的变量也是全局变量(限非严格模式)

  • 在函数内使用 var 关键字定义的变量是局部变量,即,出了函数会无效

  • 举例

/* 1.
全局变量:在函数外部声明的变量
局部变量:在函数内部声明的变量
*/
var g1 = 1;
function demo1(){
var l1 = 2;
console.log('g1 = %d, l1 = %d', g1, l1);
}
demo1();
console.log('g1 =', g1);
// console.log('l1 =', l1); // 会报错 // 2.1 小例子
var g2 = 5;
function demo2(){
console.log('g2 =', g2);
g2 = 10;
console.log('g2 =', g2);
}
console.log('g2 =', g2);
demo2();
console.log('g2 =', g2); // 2.2 小例子
var g3 = 5;
function demo3(){
console.log('g3 =', g3); // 一旦函数内部 var 了变量 n,那么函数中所有的 n 都变成了局部变量
g3 = 10;
console.log('g3 =', g3);
var g3 = 15;
console.log('g3 =', g3);
}
console.log('g3 =', g3);
demo3();
console.log('g3 =', g3); // 2.3 小例子
function demo2(){
l3 = 10; // 这里没使用 var,意为将 l3 视为全局变量(限非严格模式)
console.log('l3 =', l3);
}
demo2();
console.log('l3 =', l3); // 非严格模式下,函数内不用 var 声明的变量可以在函数外部使用
};
  • 运行结果
g1 = 1, l1 = 2
g1 = 1
g2 = 5
g2 = 5
g2 = 10
g2 = 10
g3 = 5
g3 = undefined
g3 = 10
g3 = 15
g3 = 5
l3 = 10
l3 = 10
上一篇:【JavaScript基础】Js的定时器(你想看的原理也在哟)


下一篇:socket选项总结(setsocketopt)