返回

不使用setTimeout和setInterval在页面中实现setInterval和setTimeout效果

前端

不使用setTimeout和setInterval在页面中实现setInterval和setTimeout效果

不使用setTimeout和setInterval在页面中实现setInterval和setTimeout效果

前言

昨天面试一家公司,面试官问我,如何在不使用setTimeout和setInterval在页面中实现setInterval和setTimeout效果,我:????。

后来我仔细想了一下,思路就是获得当前的时间戳,然后在需要执行的代码前面加上一个减法计算,每执行一次减去当前时间戳,当减去的结果小于等于0的时候,执行代码。

<!DOCTYPE html>
<html>
<head>
  
</head>
<body>
  <h1>不使用setTimeout和setInterval在页面中实现setInterval和setTimeout效果</h1>
  <p>
    <button id="start">开始</button>
    <button id="stop">停止</button>
  </p>
  <div id="result"></div>

  <script>
    var startTimestamp = null;
    var intervalTimestamp = 1000;
    var timeoutTimestamp = 3000;

    function start() {
      startTimestamp = Date.now();
    }

    function stop() {
      startTimestamp = null;
    }

    function update() {
      if (startTimestamp === null) {
        return;
      }

      var now = Date.now();
      var intervalDiff = now - startTimestamp - intervalTimestamp;
      var timeoutDiff = now - startTimestamp - timeoutTimestamp;

      if (intervalDiff <= 0) {
        console.log('setInterval: ' + intervalDiff);
        startTimestamp += intervalTimestamp;
      }

      if (timeoutDiff <= 0) {
        console.log('setTimeout: ' + timeoutDiff);
        startTimestamp = null;
      }

      window.requestAnimationFrame(update);
    }

    window.requestAnimationFrame(update);

    document.getElementById('start').addEventListener('click', start);
    document.getElementById('stop').addEventListener('click', stop);
  </script>
</body>
</html>

当然,这只是实现思路之一,还有其他的实现方式,但原理都是一样的,就是获得当前的时间戳,然后在需要执行的代码前面加上一个减法计算,每执行一次减去当前时间戳,当减去的结果小于等于0的时候,执行代码。