代码之家  ›  专栏  ›  技术社区  ›  TinyTiger

JavaScript重定向到另一个页面时,时间达到5分钟到小时的顶部

  •  0
  • TinyTiger  · 技术社区  · 6 年前

    我想将一个用户重定向到另一个页面时,时间达到5分钟的一个小时。

    在24小时内,这意味着我希望重定向以这样的间隔运行。。。

    • 11点55分
    • 12点55分
    • 13:55
    • 14:55分
    • 15:55分

    到目前为止,我所能想到的是像这样的JS重定向的“倒计时”风格,但我需要的不是倒计时而是基于时间(5分钟到一小时的顶部)运行的。

    setTimeout("location.href = 'https://www.google.com';",1000);

    我也试过,但什么也没发生。

    var mins = new Date().getMinutes();
    if (mins == 55) {
       window.location.href = "https://www.google.com";
    }
    

    这在JavaScript(或jQuery)中可能吗?

    2 回复  |  直到 6 年前
        1
  •  1
  •   chrisbyte    6 年前

    setTimeout()发生在指定的时间段之后,在该时间段中,定义它在1秒后触发(1000毫秒=1秒),然后它将停止,除非再次触发超时。

    一种解决方案是使用setInterval每隔1秒检查一次超时,当分钟数达到55分钟时,执行重定向。你也可以改变这个触发频率,比如每15或30秒(15000,30000)。

    // function that triggers at the interval
    function checkTimeout() {
    var now = new Date();
      var minutes = now.getMinutes();
      console.log(minutes);
      if (minutes >= 55) {
        location.href = 'https://www.google.com';
      }
    }
    
    setInterval(checkTimeout, 1000); // check interval every 1 second
        2
  •  5
  •   Seth Killian    6 年前

    你已经接近了-你只需要计算用户加载页面后剩余的时间。如果您已经在使用jQuery,我会在document.ready回调中抛出这个。

      const interval = 55*60*1000 // 55 min in ms
      const msUntilNext = interval - new Date().getTime() % interval;
      const timeout = setTimeout(() => {
         location.href = 'https://www.google.com';
      }, msUntilNext)