[英]Stop loop iterations of functions with setTimeout
My problem is when I hover over something really fast, it executes the first function and then the second function when the mouse leave the text. 我的问题是,当我将鼠标悬停在某个东西上时,它会在鼠标离开文本时执行第一个功能,然后执行第二个功能。 The two functions are executed completely.
这两个功能完全执行。 I would like something like, if the mouse leave before a specific time, do something.
我想要的是,如果鼠标在特定时间之前离开,请执行某些操作。 For instance, change the text to "Fr"
例如,将文本更改为“ Fr”
$( "#nav6" ).hover( function() { navsix(6); }, function() { <!-- clearTimeout(TO) --> nav6out(6); } ); function navsix(i) { if (window.matchMedia("(min-width: 600px)").matches) { var elem = document.getElementById("nav6"); var str = "Français"; var len = str.length + 1 - i; var TO = setTimeout(function () { elem.innerHTML = str.substring(0, len); if (--i) navsix(i); }, 50) } } function nav6out(i) { if (window.matchMedia("(min-width: 600px)").matches) { var elem = document.getElementById("nav6"); var str = "Français"; len = i + 1 var TO = setTimeout(function () { elem.innerHTML = str.substring(0, len); if (--i) nav6out(i); }, 50) } }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="topnav-right"><a id="nav6" href="#Francais">Fr</a></div>
You're on the right track with clearTimeout()
. 您在
clearTimeout()
的正确轨道上。 I added clearTimeout()
right before each of your setTimeout()
functions and declared TO
at the top. 我在每个
setTimeout()
函数之前添加了clearTimeout()
,并在顶部声明了TO
。
var TO = ""; var hoverTimeout = ""; $("#nav6").hover( function() { hoverTimeout = setTimeout(function() { navsix(6); }, 200) }, function() { clearTimeout(hoverTimeout); nav6out(6); } ); function navsix(i) { if (window.matchMedia("(min-width: 600px)").matches) { var elem = document.getElementById("nav6"); var str = "Français"; var len = str.length + 1 - i; clearTimeout(TO); TO = setTimeout(function() { elem.innerHTML = str.substring(0, len); if (--i) navsix(i); }, 50) } } function nav6out(i) { if (window.matchMedia("(min-width: 600px)").matches) { var elem = document.getElementById("nav6"); var str = "Français"; if (elem.innerHTML.length > 2) { len = i + 1; clearTimeout(TO); TO = setTimeout(function() { elem.innerHTML = str.substring(0, len); if (--i) nav6out(i); }, 50) } } }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="topnav-right"><a id="nav6" href="#Francais">Fr</a></div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.