SAP UI5函数节流(Throttle)的一个最简单的例子
生活随笔
收集整理的這篇文章主要介紹了
SAP UI5函数节流(Throttle)的一个最简单的例子
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
SAP UI5源代碼:
<!DOCTYPE html> <html> <head><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta charset="utf-8"><title>SAPUI5 Sandbox</title><scriptid="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標簽頁里也能確認,后臺請求只發送了一次:
總結
以上是生活随笔為你收集整理的SAP UI5函数节流(Throttle)的一个最简单的例子的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 电脑上共享是什么意思(ipv6是什么意思
- 下一篇: 光纤猫复位后重连方法(光纤的原理是什么)