【发布时间】:2012-03-18 05:45:11
【问题描述】:
我可以对这段代码做些什么来提高它的 CPU 效率(它现在占用了我大约 80% 的 CPU)?我昨天学习了javascript,所以可能只是我没有经验。此代码控制相当大的图块数组的转换。在鼠标悬停时,瓷砖翻转并在鼠标悬停时翻转回来。将有几个线程同时运行,我看不出有办法绕过那个。 我使用这个脚本是因为我需要以 webkit-transitions 不支持的方式准确控制转换的作用。希望 cmets 足够有意义,可以对代码有所了解。该函数是实时的,因为在加载页面时会在 javascript 中创建图块数组。之后,不再创建瓷砖。
来源可以在这里找到。我还没有工作上传。 wikisend.com/download/811662/test.zip
谢谢。
//By default, javascript will not complete a hover transition unless the mouse
remains over the entire duration of the transition. This scrip will force the hover
transition to completion.
$(document).ready(function() {
$('.tile').live('mouseenter mouseleave', (function() {
if (event.type == 'mouseover') {
var $this = $(this);
$this.addClass('hover');
//prevents mouseleave from happening when user re-enters after exiting before time is up
$this.data('box-hover-hovered', false);
//tile is not ready for leaving hover state
$this.data('box-hover-not-ready', true);
var timeout = setTimeout(function() {
//box will be ready after time is up
var state = $this.data('box-hover-hovered');
if (state) { //this is entered when user exits before
//time is up
$this.removeClass('hover');
}
$this.data('box-hover-not-ready', false);
//it's ready
}, 400); // .1 second
// Remove previous timeout if it exists
clearTimeout($this.data('box-hover-timeout'));
//stores current timer id (current timer hasn't executed yet)
$this.data('box-hover-timeout', timeout);
}
else {
var $this = $(this);
// If not not-ready, do nothing
// By default, the value is `undefined`, !undefined === true
var not_ready = $this.data('box-hover-not-ready');
if (!not_ready) {
//if user remains hovering until time is up.
$this.removeClass('hover');
} else {
//user would not have completed the action
$this.data('box-hover-hovered', true);
}
}
}));
});
【问题讨论】:
-
你有这个演示页面吗?
-
如果您要做的只是确保
hover类在对象首次悬停后至少保持应用于对象 400 毫秒,那么有很多更简单的方法可以这样做会使用更少的 CPU。但是,在写出这样的答案之前,您能否确认这就是您尝试使用此代码完成的全部工作? -
对我来说重要的是,即使用户在前 400 毫秒内将鼠标移开,从无悬停到悬停的过渡始终会完成。悬停到非悬停状态是可逆的,并且遵循转换的默认行为。所以是的,你在说什么听起来是正确的。
-
好的,我写了一个符合您要求的答案。虽然我在编写我的实现时没有查看您的实现(我只是从预期的目标出发),但我的实现与您的相似,但在一些方面更简单。
标签: javascript performance live transitions