search

Home  >  Q&A  >  body text

javascript - Why is the second parameter of s in setTimeout set to 500 milliseconds?

The following is a simple time display code:

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>当前系统时间</title>
<link rel="stylesheet" href="style.css"  />
<script language="javascript" type="text/javascript">

  window.onload = function(){
    showTime();
  }
  function checkTime(i){  //补位处理
      return i < 10 ? "0" + i : i;



  }
  function showTime(){
    var now=new Date();
    var year=  now.getFullYear();
    var month=  now.getMonth() + 1;
    var day=  now.getDate();
    var h=  now.getHours();
    var m=  now.getMinutes();
    var s=  now.getSeconds();
    h=checkTime(h)
    m=checkTime(m)
    s=checkTime(s)

    var weekday=new Array(7)
    weekday[0]="星期日"
    weekday[1]="星期一"
    weekday[2]="星期二"
    weekday[3]="星期三"
    weekday[4]="星期四"
    weekday[5]="星期五"
    weekday[6]="星期六"

    document.getElementById("show").innerHTML= year+"年"+month+"月"+day+"日 "+  " " +h+":"+m+":"+s;
    t=setTimeout('showTime()',500)
  }

</script>
</head>
<body>
<p class="content1">
  <p id="show">显示时间的位置</p>
</p>
</body>
</html>

If setTimeout is set to 1000, it will be one second slower than the actual time. Why is this?

高洛峰高洛峰2810 days ago798

reply all(4)I'll reply

  • 滿天的星座

    滿天的星座2017-06-14 10:53:04

    setTimeout(callback, time); means that after the callback callback execution ends and is delayed by time, the execution of setTimeout(); according to the single-threaded characteristics of js, may take longer than time; Here, the possible reason is that the callback also requires a certain execution time. You can check it with Chrome's Timeline; the ability is insufficient, and looking at the code, it seems that there is not much of a problem;

    reply
    0
  • 为情所困

    为情所困2017-06-14 10:53:04

    It’s very simple. The setTimeout function refers to executing the showTime function after 500 (ms) or 0.5 seconds. If it is 1000, the showTime function will be executed after 1 second. Only then will the problem you mentioned occur (purely my personal understanding ^~^).

    reply
    0
  • 女神的闺蜜爱上我

    女神的闺蜜爱上我2017-06-14 10:53:04

    No matter whether showTime is delayed by 1000 or 500, getting the time and updating the DOM are executed at the same time, so there should be no delay (unless your time calculation is wrong). And I tested it here and didn't see any delay.

    Also, why not use setInterval

    reply
    0
  • 曾经蜡笔没有小新

    曾经蜡笔没有小新2017-06-14 10:53:04

    You get the data at this time first, and then display it one second later. Of course it will be one second slower.

    reply
    0
  • Cancelreply