预解析、函数的返回值、获取非行间样式、定时器和清除定时器

预解析(声明提升)

  • JavaScript的代码在执行的过程中分为两个过程:预解析,逐行执行。
  • 预解析:声明提升,JavaScript代码在执行之前会把变量和函数的声明提升到代码的最前面,赋值部分不会提升。
// console.log(a); // undefined
// var a = 10;

// 上面两行代码相当于
// console.log(a); // undefined
// var a;
// a = 10;

// js有预解析过程:把声明提升带最前面
// var a;
// console.log(a); // undefined
// a = 10;

// 普通函数也可以预解析
// fun();
// function fun() {
//     console.log('fun');
// }

函数的返回值

  • 函数可以是 return 返回结果。
  • return的作用:
    • 结束函数的执行
    • 返回结果到函数调用处
    • 一个函数返回一个结果,一般只有一个return(分支语句除外)
    • 函数没有return,默认返回 undefined
  • 函数的返回值可以是任意数据类型。

获取非行间样式

// 封装获取样式函数 
// ele:元素 attr:样式名(字符串)
function getStyle (ele, attr) {
    // if (window.getComputedStyle) { // 标准浏览器
    //     return window.getComputedStyle(ele)[attr];
    // } else { // 低版本IE
    //     return ele.currentStyle[attr];
    // }

    return window.getComputedStyle ? window.getComputedStyle(ele)[attr] : ele.currentStyle[attr];
}

定时器

  • JavaScript中的定时器分为两种:setTimeout,setInterval

setTimeout

  • setTimeout(函数, 延迟时间):延迟固定时间执行一次函数,只会执行一次。
// setTimeout(函数, 延迟时间):延迟固定时间执行一次函数,只会执行一次。
// setTimeout(function () {
//     console.log('timeout');
// }, 2000);

function fun () {
    console.log('fun');
}
// fun();
setTimeout(fun, 2000);

setInterval

  • setInterval(函数, 间隔时间):每间隔固定时间执行一次函数。
// setInterval(函数, 间隔时间):每间隔固定时间执行一次函数。
// setInterval(function () {
//     console.log(Math.random());
// }, 1000);

function random () {
    console.log(Math.random());
}
// random();
setInterval(random, 1000);

清除定时器

  • clearTimeout(intervalId):清除延迟器。每个定时器添加后会返回一个唯一标识符(intervalId),从1开始。
  • clearInterval(intervalId):清除定时器
var t1 = setTimeout(function () {
    console.log('timeout');
}, 1000);
clearTimeout(t1);

var t2 = setInterval(function () {
    console.log('interval');
}, 1000);
clearInterval(t2);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值