SAP UI5函数节流(Throttle)的一个最简单的例子

111 阅读1分钟

SAP UI5源代码:

<!DOCTYPE html>
<html>
<head>
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta charset="utf-8">
	<title>SAPUI5 Sandbox</title>
	<script
		id="sap-ui-bootstrap"
		src="https://openui5.hana.ondemand.com/resources/sap-ui-core.js"
		data-sap-ui-theme="sap_belize"
		data-sap-ui-libs="sap.m,sap.ui.layout"
		data-sap-ui-compatVersion="edge"
		data-sap-ui-preload="async">
	</script>
	<script>
		var throttle = function(fn, delay){
     		var timer = null;
     		return function(){
        		var context = this, args = arguments;
         		clearTimeout(timer);
         		timer = setTimeout(function(){
             		fn.apply(context, args);
         		}, delay);
     		};
		};

		function getCurrentTime(){
			var date = new Date();
			var year = date.getFullYear();
			var month = date.getMonth() + 1;
			month = month<10 ? "0" + month:month;
			var day = date.getDate();
			day = day < 10 ? "0" + day:day;
			var week = "日一二三四五六".charAt(date.getDay());
			var hour = date.getHours();
			hour = hour < 10 ? "0" + hour:hour;
			var minute = date.getMinutes();
			minute = minute < 10 ? "0" + minute:minute;
			var second = date.getSeconds();
			second = second < 10 ? "0" + second:second;
				
			var current = year + "-" + month + "-" + day + " 星期" + week + " 时间" +hour + ":" + minute + ":" + second;
			return current;
		}

		function sendRequest(sInput,callback){
			console.log('request sent at time: ' + getCurrentTime() + ' with input: ' + sInput);
			jQuery.ajax({
							url:"http://localhost:3000/echo?data=" + sInput,
							dataType: 'text',
							async:true, 
							success: callback
						}
					);
		}
		var sendRequest2 = throttle(sendRequest, 3000);
		sap.ui.getCore().attachInit(function () {
			var oInput = new sap.m.Input({
				liveChange : function(oEvent) {
					var changedValue = oEvent.getParameter('newValue');

					console.log('live change event: ' + changedValue);
					sendRequest2(changedValue, (oResponse) => oResult.setText(oResponse));
				}
			});
			var oVerticalLayout = new sap.ui.layout.VerticalLayout();
			oVerticalLayout.addContent(oInput);

			var oHorizontalLayout = new sap.ui.layout.HorizontalLayout();
		
			var oLabel = new sap.m.Label({
				text: 'Response:',
				labelFor: 'result',
				design: 'Bold'
			});
		
			var oResult = new sap.m.Text('result');
			oHorizontalLayout.addContent(oLabel);
			oHorizontalLayout.addContent(oResult);

			oVerticalLayout.addContent(oHorizontalLayout);
			oVerticalLayout.placeAt("content");
		});
	</script>
</head>
<body class="sapUiBody" role="application">
	<div id="content"></div>
</body>
</html>

测试:我在一两秒之内,快速输入了12345一共五个字符,控制台里打印live change事件触发了5次,但是最后一次live change触发之后又过了三秒,请求才发送到后台:

在这里插入图片描述

network标签页里也能确认,后台请求只发送了一次:

在这里插入图片描述