setInterval定时器计时时刻测试

function formatDate(date){
	console.log(date.getFullYear()+"-"+(date.getMonth()+1)+date.getDate()+" "+date.getHours()+":"+date.getMinutes()+":"+date.getSeconds()+":"+date.getMilliseconds());
}

var timer ;
function test(){

		
	timer = setInterval(function(){
			console.log('interval');
	},30000);
	
	var startDate = new Date();
	var now = new Date();
	
	for(var i =0; i<5; i++){
		formatDate(startDate);
		// 5 second
		while(new Date () - startDate < 5*1000){
			
		}

		startDate = new Date();
	}
	
}

test();

测试setInterval开始倒计时的时刻

test函数(主逻辑)执行5×5=25秒,定时器设定为30秒后执行,

A.如果JS运行时执行到setInterval时便开始计算时间,那么test函数执行完,大概5秒(30-25)左右,开始第一次输出interval

B.如果JS运行时执行完test主逻辑以后,开始计算时间,那么test函数执行完,大概30秒,开始第一次输出interval

在chrome下输出按照A猜想执行,IE/FireFox没有测试

猜你喜欢

转载自luqingxuan.iteye.com/blog/2324135