js定时从缓存中读取数据

JavaScript设置定时从缓存中读取数据

众所周知,前端开发中为了防止用户频繁点击某个查询数据按钮,一般会采用防抖或节流的方法,以此减轻服务器的压力。
今天为大家分享另外一个方法,与防抖和节流的原理类似。从浏览器缓存中读取数据。
用户第一次进入页面时,点击查询按钮从接口请求数据,此时将数据存入缓存中,没有任何问题。
当用户后续点击时,判断距离上一次点击的时间差,假设为N秒,当超过N秒时,从接口请求数据,否则就从缓存中读取数据,以此来避免频繁的从接口请求数据,减轻服务器压力!

以下为实例代码:

<!DOCTYPE html>
<html lang="zh">
	<head>
		<meta charset="UTF-8">
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<meta http-equiv="X-UA-Compatible" content="ie=edge">
		<title></title>
		<script src="js/jquery-3.4.1.min.js" type="text/javascript" charset="utf-8"></script>
	</head>
	<body>
		<button type="button" onclick="search()">搜索</button>
		<script type="text/javascript">
			var time1 = null;
			//点击查询按钮
			function search() {
				if (time1 == null) {
					//第一次点击,从接口获取数据
					requestData();
				} else {
					//判断距离上一次从接口请求数据的时间差,10秒之内从缓存中读取数据,超过10秒则从接口请求数据,减轻服务器压力
					var timeDifference = new Date().getTime() - time1; //两次点击查询按钮的时间差值,毫秒
					if (timeDifference / 1000 < 10) {
						var res = window.localStorage.getItem("json");
						console.log('从缓存读取', JSON.parse(res))
					} else {
						requestData();
					}
				};
			};
			//从服务器接口请求数据
			function requestData() {
				time1 = new Date().getTime();
				$.ajax('http://10.132.118.125:8888/api/queryModelList', {
					data: {

					},
					dataType: 'json',
					type: 'get',
					success: function(data) {
						//设置缓存
						window.localStorage.setItem("json", JSON.stringify(data));
						var res = window.localStorage.getItem("json"); //读取缓存
						console.log('从服务器读取-------', JSON.parse(res))
					},
					error: function(xhr, type, errorThrown) {

					},
				});
			}
		</script>
	</body>
</html>

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值