setInterval()调用其他函数时候报错

(function(){
function shortcut() {

    // 配件优化
    window.topValue = 0// 上次滚动条到顶部的距离
    window.interval = null;// 定时器

    Container && Container.addEventListener("scroll", function () {
        if (interval == null)// 未发起时,启动定时器,1秒1执行
            interval = window.setInterval("test()", 1200);
        shortcutNav.style.display = "flex"
        shortcutBtnWrap.style.display = "none"
        topValue = Container.scrollTop;
    })

}

 

shortcut()

})()

上面的代码会报错,说函数test()没有定义,这是因为当使用字符串作为setInterval()第一个参数的时候,它的处理方式有点类似于在表中浏览器的window.eval(),总是在全局作用域查找函数,所以作为局部作用域中的test()函数无法被查找到。

 解决办法 :

var test = function () {
// 判断此刻到顶部的距离是否和1秒前的距离相等
if (Container && Container.scrollTop == topValue) {
// alert("scroll bar is stopping!");
shortcutNav.style.display = "none"
shortcutBtnWrap.style.display = "flex"
clearInterval(interval);
interval = null;
}
}

这样 test 在全局作用域下

posted @ 2019-10-21 10:15  八十易  阅读(1069)  评论(0编辑  收藏  举报