在 JavaScript 中使用计时器停止显示块/无闪烁
我似乎无法弄清楚这里的逻辑。我有一个隐藏的元素,直到鼠标移动 (utilBar
),并且我希望即使在计时器结束后 IF 鼠标仍在移动时它仍保持显示。显然我的想法是,在鼠标移动时启动计时器并显示元素,如果在第一个鼠标移动后有另一个鼠标移动,则停止计时器并重复启动它,因此只要鼠标移动,计时器就永远不会结束。
问题是我的元素在 1000 毫秒后闪烁,当我移动鼠标时闪烁。我想我只是在这里逻辑上绊倒,但我无法弄清楚。
//Separate function to pass in utilBarTimer into the setTimeout
function timerFunction(utilBarTimer){
self.iframe.addEventListener('mousemove',function(){
clearTimeout(window.utilBarTimer);
});
utilBar.style.display = 'none';
}
self.iframe.addEventListener('mousemove',function(){
utilBar.style.display = 'block';
var utilBarTimer = window.setTimeout(function(){
timerFunction(utilBarTimer)
},1000);
});
I can't seem to figure out the logic here. I have a an element that hides until the mouse is moved (utilBar
) and i want it to stay displayed even after the timer ends IF the mouse is still moving. Obviously what I figured was, on mouse moving start a timer and display the element and if there is another mouse move after the first one stop the timer and start it again repeatedly therefore the timer never ends as long as the mouse is moving.
the problem is my element is blinking after the 1000 milliseconds is up flashing on/off as I move the mouse. I think I'm just tripping on the logic here, but I can't figure it out.
//Separate function to pass in utilBarTimer into the setTimeout
function timerFunction(utilBarTimer){
self.iframe.addEventListener('mousemove',function(){
clearTimeout(window.utilBarTimer);
});
utilBar.style.display = 'none';
}
self.iframe.addEventListener('mousemove',function(){
utilBar.style.display = 'block';
var utilBarTimer = window.setTimeout(function(){
timerFunction(utilBarTimer)
},1000);
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您当前执行此操作的方式是创建一个新的 EventListener ,每次鼠标移动时都会清除超时。我认为您正在寻找的逻辑是这样的:
这是它的 jsfiddle在行动中。
They way you are currently doing it is creating a new
EventListener
that will clear the timeout every time the mouse moves. I think the logic you're looking for is this:Here's the jsfiddle of it in action.