zoukankan      html  css  js  c++  java
  • 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 在全局作用域下

  • 相关阅读:
    Delphi 与 C/C++ 数据类型对照表(最新的tokyo)
    Delphi新语法 For ..In
    NSwag生成客户端调用代码
    微服务
    springcloud
    NET高性能IO
    秒杀场景
    CPU开销sql server 性能调优
    WinDbg调试分析 net站点 CPU100%问题
    全链路实践Spring Cloud 微服务架构
  • 原文地址:https://www.cnblogs.com/yangwenbo/p/11711885.html
Copyright © 2011-2022 走看看