将计时器实现为js函数

时间:2011-02-21 13:04:51

标签: javascript javascript-events

嗨我已经有这个功能我试图添加这样的计时器:当值> = 1并且用户没有移动鼠标1分钟或60秒计时器启动并将用户重定向到新页面但是如果用户之前移动鼠标60秒结束计时器再次重置。

function pagar(){
var textarea = document.getElementById ("textarea");
    /*if (event.propertyName.toLowerCase () == "value") {
        alert ("NUEVO VALOR EN EL CAMPO TOTAL: " + event.srcElement.value);
        }*/
if (event.srcElement.value>=1)
{
var bottomMenu = $("#main_footer").bottomMenu([
{name:"backward","class":"red", text:getStr("menu_backward")},
{name:"menu","class":"green", text:getStr("menu_menu"), func:function(){parent.location = "./index.html";}, enabled:false},
{name:"forward","class":"green", text:getStr("menu_pay"), func:forward, enabled:true}
  ]);
  }
     else
{
var bottomMenu = $("#main_footer").bottomMenu([
    {name:"backward","class":"red", text:getStr("menu_backward")},
{name:"menu","class":"green", text:getStr("menu_menu"), func:function()       {parent.location = "./index.html";}, enabled:true},
   {name:"forward","class":"green", text:getStr("menu_pay"), func:forward, enabled:false}
 ]);
  }
     }

我想在此之后添加一个计时器

    if (event.srcElement.value>=1)
{

3 个答案:

答案 0 :(得分:1)

您需要将一个mousemove事件侦听器附加到窗口,该窗口会在移动时清除并重置计时器。

function MouseMoveTimeout() {
   // Whatever you want the timeout to do
}

var TimerID;
function InstallMouseMoveTimeout(Install) {
   var Timeout = 60000;
   var MouseMoveDetector = function(e) {
      clearTimeout(TimerID);
      TimerID = setTimeout(MouseMoveTimeout, Timeout);
   }
   if(Install && TimerID == undefined) {
      TimerID = setTimeout(MouseMoveTimeout, Timeout);
      window.addEventListener('mousemove', MouseMoveDetector, true);
   } else {
      clearTimeout(TimerID);
      window.removeEventListener('mousemove', MouseMoveDetector, true);
      TimerID = undefined;
   }
}

要在代码中使用此功能,您需要:

if (event.srcElement.value>=1) {
  InstallMouseMoveTimeout(true);  // Install mouse move timeout
  ...
} else {
  InstallMouseMoveTimeout(false); // Cancel mouse move timeout
  ...
}

答案 1 :(得分:0)

var idleTimer = null; // do this in the global scope

// do the following at the location where you want to reset the timer:
if(idleTimer) window.clearTimeout(idleTimer);
idleTimer = window.setTimeout(function() {
    location.href = 'other-site';
}, 60000);

因此,每当调用第二个代码块时,旧计时器将被重置并启动一个新计时器。但是,由于mousemove事件经常触发非常,这可能会影响性能。在这种情况下,创建一个间隔(setInterval()),触发例如每10秒钟只在mousemove处理程序中设置当前日期。然后,如果超过上次mousemove已经有足够的时间,那么你可以简单地检查你的计时器回调,在这种情况下执行一个动作。

答案 2 :(得分:0)

听起来像一个疯狂的UI想法!但是如果你想这样做,你需要在某处声明:

var timer;

如果要启动计时器,请执行以下操作:

timer = setTimeout(function() { timer = -1; doStuff(); }, seconds * 1000);

这将在doStuff过后调用seconds

如果您想取消计时器:

if (timer != -1) {
  clearTimeout(timer);
  timer = -1;
}

通过适当地组合这些,您可以解决您的问题。