setTimeout/clearTimeout问题

发布于 2024-09-04 22:35:40 字数 502 浏览 8 评论 0原文

我尝试创建一个页面以在例如之后转到起始页。 10 秒不活动(用户未点击任何地方)。其余部分我使用 jQuery,但我的测试函数中的 set/clear 是纯 JavaScript。

在我的沮丧中,我最终得到了类似这个函数的东西,我希望我可以在页面上的任何点击上调用它。计时器启动正常,但点击后不会重置。如果在前 10 秒内调用该函数 5 次,则会出现 5 个警报...没有clearTimeout...

function endAndStartTimer() {
    window.clearTimeout(timer);
    var timer;
    //var millisecBeforeRedirect = 10000; 
    timer = window.setTimeout(function(){alert('Hello!');},10000); 
}

有人有一些代码行可以解决这个问题吗? - 任意点击停止、重置并启动计时器。 - 当计时器到达时,例如。 10秒做某事。

I try to make a page to go to the startpage after eg. 10sec of inactivity (user not clicking anywhere). I use jQuery for the rest but the set/clear in my test function are pure javascript.

In my frustation I ended up with something like this function that I hoped I could call on any click on the page. The timer starts fine, but is not reset on a click. If the function is called 5 times within the first 10 seconds, then 5 alerts will apear... no clearTimeout...

function endAndStartTimer() {
    window.clearTimeout(timer);
    var timer;
    //var millisecBeforeRedirect = 10000; 
    timer = window.setTimeout(function(){alert('Hello!');},10000); 
}

Any one got some lines of code that will do the trick?
- on any click stop, reset and start the timer.
- When timer hits eg. 10sec do something.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

风为裳 2024-09-11 22:35:40

您需要在函数外部声明timer。否则,您将在每次函数调用时获得一个全新的变量。

var timer;
function endAndStartTimer() {
  window.clearTimeout(timer);
  //var millisecBeforeRedirect = 10000; 
  timer = window.setTimeout(function(){alert('Hello!');},10000); 
}

You need to declare timer outside the function. Otherwise, you get a brand new variable on each function invocation.

var timer;
function endAndStartTimer() {
  window.clearTimeout(timer);
  //var millisecBeforeRedirect = 10000; 
  timer = window.setTimeout(function(){alert('Hello!');},10000); 
}
我做我的改变 2024-09-11 22:35:40

问题在于计时器变量是本地变量,每次函数调用后其值都会丢失。

您需要保留它,可以将其放在函数之外,或者如果您不想将变量公开为全局变量,则可以将其存储在 闭包,例如:

var endAndStartTimer = (function () {
  var timer; // variable persisted here
  return function () {
    window.clearTimeout(timer);
    //var millisecBeforeRedirect = 10000; 
    timer = window.setTimeout(function(){alert('Hello!');},10000); 
  };
})();

The problem is that the timer variable is local, and its value is lost after each function call.

You need to persist it, you can put it outside the function, or if you don't want to expose the variable as global, you can store it in a closure, e.g.:

var endAndStartTimer = (function () {
  var timer; // variable persisted here
  return function () {
    window.clearTimeout(timer);
    //var millisecBeforeRedirect = 10000; 
    timer = window.setTimeout(function(){alert('Hello!');},10000); 
  };
})();
屋檐 2024-09-11 22:35:40

这是因为计时器是函数的局部变量。

尝试在函数之外创建它。

That's because timer is a local variable to your function.

Try creating it outside of the function.

若能看破又如何 2024-09-11 22:35:40

在 React 中使用此方法的一种方法:

class Timeout extends Component {
  constructor(props){
    super(props)

    this.state = {
      timeout: null
    }

  }

  userTimeout(){
    const { timeout } = this.state;
    clearTimeout(timeout);
    this.setState({
      timeout: setTimeout(() => {this.callAPI()}, 250)
    })

  }
}

例如,如果您只想在用户停止输入后调用 API,则很有帮助。 userTimeout 函数可以通过 onKeyUp 绑定到输入。

A way to use this in react:

class Timeout extends Component {
  constructor(props){
    super(props)

    this.state = {
      timeout: null
    }

  }

  userTimeout(){
    const { timeout } = this.state;
    clearTimeout(timeout);
    this.setState({
      timeout: setTimeout(() => {this.callAPI()}, 250)
    })

  }
}

Helpful if you'd like to only call an API after the user has stopped typing for instance. The userTimeout function could be bound via onKeyUp to an input.

小兔几 2024-09-11 22:35:40

不确定这是否违反了一些好的实践编码规则,但我通常会提出这样的规则:

if(typeof __t == 'undefined')
        __t = 0;
clearTimeout(__t);
__t = setTimeout(callback, 1000);

这可以防止需要在函数之外声明计时器。

编辑:这也不会在每次调用时声明新变量,但始终回收相同的变量。

希望这有帮助。

Not sure if this violates some good practice coding rule but I usually come out with this one:

if(typeof __t == 'undefined')
        __t = 0;
clearTimeout(__t);
__t = setTimeout(callback, 1000);

This prevent the need to declare the timer out of the function.

EDIT: this also don't declare a new variable at each invocation, but always recycle the same.

Hope this helps.

面犯桃花 2024-09-11 22:35:40

使用 Jquery 制作下拉菜单的实际示例!
当鼠标悬停在 #IconLoggedinUxExternal 上时,会显示 div#ExternalMenuLogin 并设置超时以隐藏 div#ExternalMenuLogin

当鼠标悬停在 div#ExternalMenuLogin 上时,它会取消超时。
当鼠标移到 div#ExternalMenuLogin 上时,它会设置超时。

这里的重点是始终在设置超时之前调用clearTimeout,这样可以避免重复调用

var ExternalMenuLoginTO;
$('#IconLoggedinUxExternal').on('mouseover mouseenter', function () {

    clearTimeout( ExternalMenuLoginTO )
    $("#ExternalMenuLogin").show()
});

$('#IconLoggedinUxExternal').on('mouseleave mouseout', function () {

    clearTimeout( ExternalMenuLoginTO )    
    ExternalMenuLoginTO = setTimeout(
        function () {

            $("#ExternalMenuLogin").hide()

        }
        ,1000
    );
    $("#ExternalMenuLogin").show()
});

$('#ExternalMenuLogin').on('mouseover mouseenter', function () {

    clearTimeout( ExternalMenuLoginTO )
});
$('#ExternalMenuLogin').on('mouseleave mouseout', function () {

    clearTimeout( ExternalMenuLoginTO )
    ExternalMenuLoginTO = setTimeout(
        function () {

            $("#ExternalMenuLogin").hide()

        }
        ,500
    );
});

Practical example Using Jquery for a dropdown menu !
On mouse over on #IconLoggedinUxExternal shows div#ExternalMenuLogin and set time out to hide the div#ExternalMenuLogin

On mouse over on div#ExternalMenuLogin it cancels the timeout.
On mouse out on div#ExternalMenuLogin it sets the timeout.

The point here is always to invoke clearTimeout before set the timeout, as so, avoiding double calls

var ExternalMenuLoginTO;
$('#IconLoggedinUxExternal').on('mouseover mouseenter', function () {

    clearTimeout( ExternalMenuLoginTO )
    $("#ExternalMenuLogin").show()
});

$('#IconLoggedinUxExternal').on('mouseleave mouseout', function () {

    clearTimeout( ExternalMenuLoginTO )    
    ExternalMenuLoginTO = setTimeout(
        function () {

            $("#ExternalMenuLogin").hide()

        }
        ,1000
    );
    $("#ExternalMenuLogin").show()
});

$('#ExternalMenuLogin').on('mouseover mouseenter', function () {

    clearTimeout( ExternalMenuLoginTO )
});
$('#ExternalMenuLogin').on('mouseleave mouseout', function () {

    clearTimeout( ExternalMenuLoginTO )
    ExternalMenuLoginTO = setTimeout(
        function () {

            $("#ExternalMenuLogin").hide()

        }
        ,500
    );
});
小忆控 2024-09-11 22:35:40

这效果很好。这是我为处理保留事件而创建的管理器。有需要等待和放手的事件。

function onUserHold(element, func, hold, clearfunc) {
    //var holdTime = 0;
    var holdTimeout;

    element.addEventListener('mousedown', function(e) {
        holdTimeout = setTimeout(function() {
            func();
            clearTimeout(holdTimeout);
            holdTime = 0;
        }, hold);
        //alert('UU');
    });

    element.addEventListener('mouseup', clearTime);
    element.addEventListener('mouseout', clearTime);

    function clearTime() {
        clearTimeout(holdTimeout);
        holdTime = 0;
        if(clearfunc) {
            clearfunc();
        }
    }
}

元素参数是您持有的参数。 func 参数在其保持参数指定的毫秒数时触发。 clearfunc 参数是可选的,如果给出了它,那么当用户放开或离开该元素时,它将被触发。您还可以采取一些变通办法来获得您想要的功能。享受! :)

This works well. It's a manager I've made to handle hold events. Has events for hold, and for when you let go.

function onUserHold(element, func, hold, clearfunc) {
    //var holdTime = 0;
    var holdTimeout;

    element.addEventListener('mousedown', function(e) {
        holdTimeout = setTimeout(function() {
            func();
            clearTimeout(holdTimeout);
            holdTime = 0;
        }, hold);
        //alert('UU');
    });

    element.addEventListener('mouseup', clearTime);
    element.addEventListener('mouseout', clearTime);

    function clearTime() {
        clearTimeout(holdTimeout);
        holdTime = 0;
        if(clearfunc) {
            clearfunc();
        }
    }
}

The element parameter is the one which you hold. The func parameter fires when it holds for a number of milliseconds specified by the parameter hold. The clearfunc param is optional and if it is given, it will get fired if the user lets go or leaves the element. You can also do some work-arounds to get the features you want. Enjoy! :)

请别遗忘我 2024-09-11 22:35:40
<!DOCTYPE html>
<html>

<body>

  <h2>EJEMPLO CONOMETRO CANCELABLE</h2>

  <button onclick="inicioStart()">INICIO</button>
  <input type="text" id="demostracion">
  <button onclick="finStop()">FIN</button>

  <script>
    let cuenta = 0;
    let temporalTiempo;
    let statusTime = false;


    function cronometro() {
      document.getElementById("demostracion").value = cuenta;
      cuenta++;
      temporalTiempo = setTimeout(cronometro, 500);
    }

    function inicioStart() {
      if (!Boolean(statusTime)) {
        statusTime = true;
        cronometro();
      }
    }

    function finStop() {
      clearTimeout(temporalTiempo);
      statusTime = false;

    }
  </script>

</body>

</html>

<!DOCTYPE html>
<html>

<body>

  <h2>EJEMPLO CONOMETRO CANCELABLE</h2>

  <button onclick="inicioStart()">INICIO</button>
  <input type="text" id="demostracion">
  <button onclick="finStop()">FIN</button>

  <script>
    let cuenta = 0;
    let temporalTiempo;
    let statusTime = false;


    function cronometro() {
      document.getElementById("demostracion").value = cuenta;
      cuenta++;
      temporalTiempo = setTimeout(cronometro, 500);
    }

    function inicioStart() {
      if (!Boolean(statusTime)) {
        statusTime = true;
        cronometro();
      }
    }

    function finStop() {
      clearTimeout(temporalTiempo);
      statusTime = false;

    }
  </script>

</body>

</html>

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文