search

Home  >  Q&A  >  body text

javascript - What is the role of var xxx=null in front of the delayed execution function setTimeout?

Sorry for posting this for the first time..
I want to make an effect and execute some functions after the mouse stays on p for two seconds. It will not be executed for more than two seconds;
Then I found the setTimeout function online and successfully solved it. , because I have always been self-taught, so my foundation is weak. Please help me with some things I don’t understand

A total of three questions are commented in the code, thank you very much!
Code:

<script src="jquery.min.js"></script>
<script>
        var timer = null; // 1.此处为什么要在这里声明timmer=null?
        $(function(){
            $("#test").hover(
            function(){
                $(this).html("悬停");
                timer=setTimeout(function(){alert("hello")},2000); // 2.为什么不能直接去掉第
                //一行的声明 ,在此处var timer=setTimeout(...)...
            },
            function(){
                if(timer)  // 3.这里的if语句有什么作用?我试着去掉后函数也能完整运行呀
                    clearTimeout(timer);
                $(this).html("测试"); 
                });
        });   
    </script>
</head>
<body>
    <p id="test">
        测试
    </p>
</body>
伊谢尔伦伊谢尔伦2755 days ago569

reply all(3)I'll reply

  • 世界只因有你

    世界只因有你2017-05-19 10:40:43

    1. setTimeout will return an integer id, which is the timer number. Declaring a variable in advance is naturally used to store the number;

    2. Why can’t it be stated here? Want to know where to find this variable? var是函数作用域的,在function里边声明的变量一出去就没了,你叫另一个匿名函数的clearTimeout

    3. The if here is mainly rigorous. When

      successfully returns the timer number (because the initial value is null, if it does not return, it will definitely be false), then clearTimeout(timer )This sentence prevents the error code from continuing to execute when the previous execution error occurs. if主要是严谨,在setTimeout成功返回计时器编号(因为初始是null,如果没返回肯定就false了)的情况下,才会执行clearTimeout(timer)

    4. reply
      0
  • ringa_lee

    ringa_lee2017-05-19 10:40:43

    First of all, the setTimeout timer will be cleared after use. In order to know which timer to clear, a variable must be added, which is the timer change.
    Secondly, function scope. Internal variables cannot be directly accessed outside the function, so a variable must be defined outside the function for use by different functions.
    The last if(timer) is mainly to avoid triggering the clear error when the timer has been closed.

    reply
    0
  • 某草草

    某草草2017-05-19 10:40:43

    Thank you both above!

    reply
    0
  • Cancelreply