2010-08-31 67 views
1
var focus = true; 

function z() { 
    this.t = 0; 
    this.p = function (t) { 
     if (focus == true) { 
      this.t = t; 
      alert(this.t); 

     } 

    } 
} 
var zp = new z(); 
setTimeout('zp.p(0)', 100); 
window.setInterval('zp.p(1)', 2000); 
var ftimer = setTimeout('focus=false', 2000); 

document.addEventListener('mousemove', function (e) { 
    clearTimeout(ftimer); 
    focus = true; 
    ftimer = setTimeout('focus=false', 2000); 
}, false); 

我有这段代码。但由于某种原因,即使连续移动鼠标,它也只会提醒两次。我一直在研究这个问题,并且正在调查萤火虫,当我移动我的鼠标时,重点是真实的。我一直想弄清楚发生了什么......即使我这样做:即使我这样做:javascript setInterval对象的函数只能调用2x

function z() { 
    this.t = 0; 
    this.p = function (t) { 
     if (focus == true) { 
      this.t = t; 

     } 
     alert(this.t); 

    } 
} 

它仍然只警报两次。

我曾尝试使用循环setTimeout函数,但也不工作。这让我疯狂。

+0

它似乎不断警告我。 – palswim 2010-08-31 16:03:16

+1

你想做什么?它总是向我发出警告,似乎没有任何特别的用处。在'setTimeout'中使用字符串也会使用'eval'这个邪恶的东西,在这种情况下使用匿名函数。你应该告诉我们这是什么预期的效果,或者重构你的代码来表明它。因为谁知道'z'是什么。 – 2010-08-31 16:14:29

回答

0

很好,你找到了你的错误。

我会使用更多的比特的功能-AS-一流的对象和更少eval逻辑编写代码:

var focus = true; 
function z() { 
    var that = this; // we won't always have the correct value of "this" 
    this.focus = true; 
    this.t = 0; 
    this.p = function (t) { 
     if (that.focus == true) { 
      that.t = t; 
      alert(t); 
     } 
    } 
    this.fade = (function(obj){ return function(){ obj.focus = false; } })(this); // Using self-invokation 
} 
var zp = new z(); 
setTimeout(zp.p, 100, 0); 
window.setInterval(zp.p, 2000, 1); 
var ftimer = setTimeout(zp.fade, 2000); 
document.addEventListener('mousemove', function (e) { 
    clearTimeout(ftimer); 
    zp.focus = true; 
    ftimer = setTimeout(zp.fade, 2000); 
}, false); 

我用线路10a self-invoking function(function(obj){ return function(){...} })(this);,和set this to a different variable

+0

感谢您的支持!对此,我真的非常感激。 – DantheMan 2010-08-31 17:42:00

0

我发现它只是和firefox相关,而且firefox在一行代码中窒息,所以这就是为什么它不会运行。所以我解决了这个问题,现在一切都很好。

+0

你的代码肯定是次优的,如果你说出你实际上正在做的事情,人们可以(也可能会)想出一个更好的版本。 – Tomalak 2010-08-31 16:21:12

相关问题