首页 > Web开发 > 详细

JS常用函数总结

时间:2020-03-10 18:09:40      阅读:72      评论:0      收藏:0      [点我收藏+]

节流防抖

// 节流函数
// 立即执行 在单位时间内只触发一次事件
const throttle = (method, delay) => {
    let timer = null;
    let start = false;
    return function () {
        if (!start) {
            start = true;
            method.apply(this, arguments);
            timer = setTimeout(() => {
                start = false;
            }, delay);
        }
    };
};
// let test = throttle(function () {
//     console.log(‘节流‘)
// }, 1000);
// test();
// setTimeout(() => {
//     test();
// }, 500);
// setTimeout(() => {
//     test();
// }, 3000);

// 防抖函数
// 延迟执行 在事件被触发单位时间内 又被触发 则重新计时
const debounce = (method, delay) => {
    let timer = null;
    let start = null;
    return function () {
        let now = Date.now();
        if (!start) {
            start = now;
        }
        if (now - start > delay) {
            method.apply(this, arguments);
            start = now;
        } else {
            clearTimeout(timer);
            timer = setTimeout(() => {
                method.apply(this, arguments);
            }, delay);
            start = now;
        }
    };
};
// let test = debounce(function () {
//     console.log(‘防抖‘)
// }, 1000);
// test();
// setTimeout(() => {
//     test();
// }, 500);
// setTimeout(() => {
//     test();
// }, 1000);
// setTimeout(() => {
//     test();
// }, 3000);

 

点击复制

// 点击实现copy
const copy = (val) => {
    let input = document.createElement(‘input‘);
    input.value = val;
    document.body.appendChild(input);
    input.select();
    input.setSelectionRange(0, input.value.length);
    document.execCommand(‘Copy‘);
    document.body.removeChild(input);
    console.log(‘复制成功‘)
};
// copy(‘文本‘);

 

JS常用函数总结

原文:https://www.cnblogs.com/QQPrincekin/p/12456646.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!