JS定时器实现页面N秒后跳转 实现每隔 1s 自动刷新页面并格式化的显示当前时间

1. 通过 setInterval 函数,来周期性的更新倒计时间,同时更新到页面。即通过设置页面可以显示 3 2 1,然后跳转。1000指的是每隔1秒执行一次。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div class="one"></div>
<script>
    let timer = 3; // 设置跳转时间
    let div = document.querySelector('.one');
    setInterval(function() {
        if(timer==0) {
            location.href = "http://www.baidu.com"; //跳转目的地
        } else {
            div.innerHTML = "您将在"+timer+"秒后跳转到百度";
            timer--;
        }
    },1000);  // 1000毫秒 一秒执行一次
</script>
</body>
</html>

2. 通过 setTimeout 执行一个延迟函数来达到跳转的目的。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h3>将在3秒后跳转到百度页面</h3>
    <script>
        setTimeout(function() {
            window.location.href = "http://www.baidu.com";
        },3000); // 3000毫秒 在这设置跳转时间
    </script>
</body>
</html>

 


3. SimpleDateFormat

//第一种
@WebServlet("/aaa")
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf8");
        resp.setContentType("text/html;charset=utf8");
        // 设置刷新时间为一秒
        resp.setHeader("Refresh","1");
        // 格式化日期
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  //这种是24小时制
        //DateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");  //这种是12小时制
        String format1 = format.format(new Date());
        resp.getWriter().write("当前时间  "+format1);
    }




//第二种
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html; charset=utf-8");
        // 设置Refresh时间为1秒
        resp.setHeader("Refresh", "1");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 24小时制
        String time = sdf.format(new Date());
        resp.getWriter().write("当前时间:" + time);
    }

 或者

@WebServlet("/aaa")
public class test extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html; charset=utf-8");
        // 设置Refresh时间为1秒
        resp.setHeader("Refresh", "1");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = sdf.format(new Date());
        resp.getWriter().write("当前时间:" + time);
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

去北极避暑~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值