• 中央定时器控制


    浏览器不会对特定interval处理程序的多个实例进行队列

    由于javascript在执行时,页面渲染的所有更新操作都要暂停,所有利用定时器分解长时间运行的任务,用于提升用户体验。

    中央定时器:

    1. 每个页面在同一时间只需要运行一个定时器

    2. 可以根据需要暂停和恢复定时器

    3.删除回调函数的过程变得简单

    <!DOCTYPE html>
    <html lang="en">
    <head>
    	<meta charset="UTF-8">
    	<title>timers</title>
    </head>
    <body>
    	<div id="box" style="display: inline-block; position: absolute;">hello</div>
    </body>
    <script>
    	window.onload=function(){
    		var timers = {
    			timerId: 0,
    			timers: [],
    			add: function(fn){
    				this.timers.push(fn);
    			},
    			start: function(){
    				if(this.timerId) return;
    				(function runNext(){
    					for(var i = 0; i < timers.timers.length; i++){
    						if(timers.timers[i]() === false){
    							timers.timers.splice(i,1);
    							i--;
    						}
    					}
    					timers.timerId = setTimeout(runNext, 0);
    				})()
    			},
    			stop: function(){
    				clearTimeout(this.timerId);
    				this.timerId = 0;
    			}
    		}
    
    		var box = document.getElementById('box'), x=0, y=0;
    
    		timers.add(function(){
    			box.style.left = x + 'px';
    			console.log('x')
    			if(++x > 50) return false;
    		});
    		timers.add(function(){
    			box.style.top = y + 'px';
    			console.log('y')
    			y += 2;
    			if(y > 120) return false; 
    		});
    
    		timers.start();
    	}
    </script>
    </html>
    

    在大多数情况下,是使用闭包来给定时器传递数据的,但现代浏览器(IE9以上),也允许我们在声明定时器的时候传入参数

    for(var i =1 ; i< 4; i++){
        setTimeout(function(i){console.log(i)},100,i)
    }
    
    for(var i =1 ; i< 4; i++){
        (function(i){
             setTimeout(function(){console.log(i)},100)        
        })
    }
    
    setTimeout(function runNext(){
        console.log("In");
        setTimeout(runNext, 10);        
    },10)
  • 相关阅读:
    IntelliJ idea 2021.3 安装使用及激活
    高项-信息系统基础-UML图
    软考高项(信息系统项目管理师)介绍
    Android Studio中的Gradle面板没有Task任务列表如何找回?
    ubuntu 安装nodejs,npm,
    解决video.js video-player不能自动播放问题
    vuex开启namespaced
    axios提交body raw格式
    vue配置服务代理
    PIDFile没有配置导致将mongodb配置成服务时启动失败
  • 原文地址:https://www.cnblogs.com/luguiqing/p/8263475.html
Copyright © 2020-2023  润新知