zoukankan      html  css  js  c++  java
  • 怎样推迟某个函数的执行

    方法1: 使用setTimeout();

    function sayHi(){
        alert("Hi.");
    }
    
    setTimeout(sayHi, 2000);

    方法2: 使用window.requestAnimationFrame();

    var element = document.getElementById('animate');
    element.style.position = 'absolute';
    
    var start = null;
    
    function step(timestamp) {
      if (!start) start = timestamp;
      var progress = timestamp - start;
      // 元素不断向左移,最大不超过200像素
      element.style.left = Math.min(progress / 10, 200) + 'px';
      // 如果距离第一次执行不超过 2000 毫秒,
      // 就继续执行动画
      if (progress < 2000) {
        window.requestAnimationFrame(step);
      }
    }
    
    window.requestAnimationFrame(step);

    两者区别: 

    setTimeout()需要手动设置延迟时间, 而requestAnimationFrame()则是会推迟到浏览器下一次重流时执行. 因此, 前者比较通用, 后者主要是放一些需要操作DOM的方法函数, 这样有利于提升性能;

    注意:

    window.cancelAnimationFrame()可以用于取消其内回调函数的执行.

    方法3: 使用window.requestIdleCallback()将内部函数推迟到系统资源空闲时执行;

    用法和window.requestAnimationFrame()类似, 只是推迟条件不同. 同时也有一个取消执行的方法: window.cancelIdleCallback()

    requestIdleCallback(myNonEssentialWork);
    
    function myNonEssentialWork(deadline) {
      while (deadline.timeRemaining() > 0) {
        doWorkIfNeeded();
      }
    }
  • 相关阅读:
    android_自定义布局
    二叉树_学习笔记
    栈的应用-四则表达式(C#代码实现)
    Android Fragment 生命周期
    Android Fragment之间传值
    Android ArrayAdpater 填充集合
    任务和返回栈
    XML Drawable与9-Patches
    《python语言程序设计》_第一章编程题
    CSS-文本超出部分省略号
  • 原文地址:https://www.cnblogs.com/aisowe/p/11718583.html
Copyright © 2011-2022 走看看