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>
setTimeout
will return an integer id, which is the timer number. Declaring a variable in advance is naturally used to store the number;Why can’t it be stated here? Want to know where to find this variable?
var
是函数作用域的,在function
里边声明的变量一出去就没了,你叫另一个匿名函数的clearTimeout
if
here is mainly rigorous. Whensuccessfully 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)
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.
Thank you both above!