实现相对准时的setTimeout

2023-12-27 19:00:36

1 原生setTimeout实现

?
// 原生setTimeout执行
	let form ={}	
	function timer() { 
		var speed = 50, // 设定间隔 
		counter = 1,  // 计数 
		start = new Date().getTime(); 
		function instance() 
		{ 
			var ideal = (counter * speed), 
			real = (new Date().getTime() - start); 
			var diff = (real - ideal); 
			counter++; 

			form.ideal = ideal; // 记录理想值 
			form.real = real;   // 记录真实值 
			form.diff = diff;  // 差值 
			console.log(form)
			if(form.ideal < 2583){
				window.setTimeout(function() { instance(); }, speed); 
			}
		}; 
		window.setTimeout(function() { instance(); }, speed); 
	} 
	// 启动原生setTimeout测试
	timer();

?

结果:相差时间越来越长

2??requestAnimationFrame 方式实现,根据浏览器的刷新频率1s 60次

// requestAnimationFrame
	function animationFrame () { 
		let startTime = Date.now() 
		 
		var speed = 17 // 设定间隔 
		var counter = 0  // 计数 
		var start = new Date().getTime(); 
		function loop () { 
			const now = Date.now() 
			var ideal = (counter * speed)
			var real = (new Date().getTime() - start); 
			var diff = (real - ideal); 
			counter++

			form.ideal = ideal; // 记录理想值 
			form.real = real;   // 记录真实值 
			form.diff = diff;  // 差值 
			
			console.log(form)
			if(now - startTime < 2000) {
				requestAnimationFrame(loop) 
			}
			
		} 
		loop()
	}
	animationFrame()

结果:时间比较准 但是不能调整 越16 17 ms执行一次

3 setTimeout 通过系统时间补偿实现

// 系统时间补偿
	function timercom() { 
	    var speed = 50, 
	    counter = 1,  
	    start = new Date().getTime(); 
		
	    function instance() { 
			var real = (counter * speed), 
			ideal = (new Date().getTime() - start); 
			var diff = (ideal - real); 
			counter++; 
			form.ideal = ideal; // 记录理想值 
			form.real = real;   // 记录真实值 
			form.diff = diff; // 差值
			console.log(form)
			
			if(form.ideal < 3500){
				window.setTimeout(function() { instance(); }, (speed - diff)); // 通过系统时间进行修复 
			
			}
	    }; 
		
	   	window.setTimeout(function() { instance(); }, speed); 
	} 
	// 启动系统时间补偿测试
	timercom()

结果:时间可以设定 相差结果很小

文章来源:https://blog.csdn.net/liuxiaochang_2011/article/details/135245822
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。