前言
定时器是 JS 逆向中不可忽视的一环,它既是反爬、反调试的 “武器”,也可能是暴露核心逻辑的 “线索”创建两种不同的定时器
第一种
setTimeout(function () {
console.log('hello world')
}, 1000) // 毫秒为单位,1000毫秒之后执行function
此定时器是过段时间(这里是1s)执行一次回调,打印出hello world 打印一次后自动停止
第二种
setInterval(function () {
console.log('hello world')
}, 1000) // 毫秒为单位,每过1000毫秒就执行function
此定时器会每过1s后就执行一次回调永不停止,那如何关闭定时器呢
关闭定时器
clearInterval方法关闭
// 先创建一个定时器用变量接收
var noneClosed = setInterval(function () {
console.log('hello world')
}, 1000)
// 将变量传入关闭定时器
clearInterval(noneClosed)
这里其实有个问题,程序运行这几行一定比1s快,所以没等回调函数打印出hello world呢就直接关闭定时器了,不过我们可以像py中使用time模块等待运行后再关闭定时器,js中用的是setTimeout,如下:
// 1. 创建定时器,变量接收返回的标识
var timer = setInterval(function () {
console.log('hello world');
}, 1000);
// 2. 延迟 1500 毫秒后关闭定时器
setTimeout(function () {
clearInterval(timer);
console.log('定时器已关闭');
}, 1500);
或者用交互,点击某个按钮后停止,这里先不研究,知道即可
方法置空
var setInterval = function (re) { // 方法置空,重写settInterval方法使其只执行一次
re()
}
var rewriteFuncTime = setInterval(function () { // 重写方法后就只会进行一次了
console.log('hello world')
}, 1000)
第一个重写setInterval方法的函数形参re传入的是一个回调函数,没有第二个形参,所以时间没传进去,所以setInterval方法和时间就没关系了,所以运行几次’定时器’中的回调函数就由调用几次re()有关系了