Skip to content

setTImeout & setInterval 查漏补缺 #31

Description

@Calerme

this 指向

const value = 'window';
const obj = { value: 'obj', show () { console.log(this.value) } };
setTimeout(obj.show, 1000); // -> 'window'
setTImeout(function () { obj.show(); }, 1000); // -> 'obj'

使用 setInterval 进行轮询

let hash = window.location.hash;
let hashWatcher = setInterval(function () {
    if (window.location.hash !== hash) {
        updatePage();
    }
}, 1000);

使用 setTImeout 进行进行轮询

setTimeout 可以保证代码每次执行的间隔相同。

setTimeout( function f() {
    // doSomething
    setTimeout(f, 2000);
}, 2000);

debounce (防抖)函数

$('textarea').on('keydown', debounce(ajaxAction, 2500));

function debounce(fn, delay) {
    var timer = null;
    return function () {
        clearTImeout(timer);
        timer = setTImeout(fn, delay);
    }
}

参考

JavaScript 标准参考教程

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions