jquery 在js函数中实现定时器

iq3niunx  于 2023-01-08  发布在  jQuery
关注(0)|答案(3)|浏览(153)

我已经有了这个函数,我尝试添加一个计时器,如下所示:当值〉= 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)
{
nimxete2

nimxete21#

您可能需要在窗口上附加一个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
  ...
}
aelbi1ox

aelbi1ox2#

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以来的足够时间,并在这种情况下执行一个操作。

wpcxdonn

wpcxdonn3#

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

var timer;

当您想要启动计时器运行时,请执行以下操作:

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

它将在seconds过去后调用doStuff
如果要取消计时器:

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

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

相关问题