Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

第 06 题:实现一个打点计时器 #6

Open
doubleyao5753 opened this issue Jul 28, 2019 · 1 comment
Open

第 06 题:实现一个打点计时器 #6

doubleyao5753 opened this issue Jul 28, 2019 · 1 comment

Comments

@doubleyao5753
Copy link
Owner

doubleyao5753 commented Jul 28, 2019

setInterval( ) 无限定时器

重温:

  • 定时器是window下的方法
  • setInterval() 方法会不停地调用函数,直到 clearInterval() 被调用或窗口被关闭。由 setInterval() 返回的 ID 值可用作 clearInterval() 方法的参数。
function count(start, end) {
    // 首先立即输出第一个
    console.log(start++)
    // 设置定时器并命名,比较起点终点大小
    var timer = setInterval(function(){
        start<=end? console.log(start++):clearInterval(timer)
    },100)
    // 返回带有清除定时器方法的对象
    return {
        cancel: function(){
            clearInterval(timer)
        }
    }
}
@doubleyao5753
Copy link
Owner Author

setTimeout( ) 一次定时器 + 递归 不推荐

一次定时器只会执行一次里面的函数,清除为clearTimeout()

// setTimeout 不推荐
function count2(start , end) {
    if (start <= end) {
        console.log(start)
        start++;
        var timer = setTimeout(function(){count(start,end)},100)
    }
    return {
        cancel: function(){
            clearTimeout(timer)
        }
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant