博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
JS高级用法
阅读量:4318 次
发布时间:2019-06-06

本文共 2326 字,大约阅读时间需要 7 分钟。

 1、重复定时器

 

setTimeout(function() {    // 处理中        setTimeout(arguments.callee, 1000);}, 1000)

 

这种模式链式调用了 setTimeout(), 每次函数执行的时候都会创建一个新的定时器,

第二个 setTimeout() 的调用使用了 arguments.callee 来获取对当前执行函数的引用,并为其设置另外一个定时器。
这样做的好处是在前一个定时器代码执行完之前,不会向队列插入新的定时器代码,确保不会有任何缺失的间隔。

 

2、数组分块处理

function chunk(array, process, context) {    setTimeout(function() {        var item = array.shift();        process.call(context, item);                if (array.length > 0) {            setTimeout(arguments.callee, 1000);        }    }, 1000);}

用法:

var data = [12, 123, 234, 345, 456, 567];function printValue(item) {    console.log(item);}chunk(data, printValue);

数组分块的重要性在于他可以将多个项目的处理在执行队列上分开,在每个项目处理之后,给予其他的浏览器处理机会运行,

这样就可能避免长时间运行脚本的错误。

 

3、节流函数

function throttle(method, context) {    clearTimeout(method.tID);    method.tID = setTimeout(function () {        method.call(context);    }, 1000);}

用法:

function showTime() {    console.log("nowDate:" + new Date().toLocaleDateString());}setInterval(function () {    throttle(showTime);}, 2000);

 

4、自定义事件

function EventTarget() {    this.handlers = {};}EventTarget.prototype = {    constructor: EventTarget,    addHandler: function (type, handler) {        if (typeof this.handlers[type] == "undefined") {            this.handlers[type] = [];        }        this.handlers[type].push(handler);    },    fire: function (event) {        if (!event.target) {            event.target = this;        }        if (this.handlers[event.type] instanceof Array) {            var handlers = this.handlers[event.type];            for (var i = 0, len = handlers.length; i < len; i++) {                handlers[i](event);            }        }    },    removeHandler: function (type, handler) {        if (this.handlers[type] instanceof Array) {            var handlers = this.handlers[type];            for (var i = 0, len = handlers.length; i < len; i++) {                if (handlers[i] == handler) {                    break;                }            }            handlers.splice(i, 1);        }    }};

用法:

function handleMessage(event) {    alert("Message received: " + event.message);}var target = new EventTarget();target.addHandler("message", handleMessage);target.fire({type: "message", message: "Hello World"});target.removeHandler("message", handleMessage);

 

转载于:https://www.cnblogs.com/lidgblogs/p/7251269.html

你可能感兴趣的文章
Notes on <High Performance MySQL> -- Ch3: Schema Optimization and Indexing
查看>>
Alpha冲刺(10/10)
查看>>
数组Array的API2
查看>>
为什么 Redis 重启后没有正确恢复之前的内存数据
查看>>
No qualifying bean of type available问题修复
查看>>
第四周助教心得体会
查看>>
spfile
查看>>
Team Foundation Service更新:改善了导航和项目状态速查功能
查看>>
WordPress资源站点推荐
查看>>
Python性能鸡汤
查看>>
android Manifest.xml选项
查看>>
Cookie/Session机制具体解释
查看>>
ATMEGA16 IOport相关汇总
查看>>
JAVA基础-多线程
查看>>
面试题5:字符串替换空格
查看>>
[Codevs] 线段树练习5
查看>>
Amazon
查看>>
component-based scene model
查看>>
Echart输出图形
查看>>
hMailServer搭建简单邮件系统
查看>>