I believe that web front-end developers have more or less encountered throttling and anti – shake problems. Function throttling and function stabilization, both of which are a means to optimize the efficiency of executing code. More code execution is not always better in a given amount of time. On the other hand, frequently triggering or executing code can cause a lot of redraw problems that affect browser or machine resources. So keep the number of times your code is executed within a reasonable range. Not only can save browser CPU resources, but also can make the page browse more smoothly, not because of the execution of JS and the occurrence of lag. That’s what function throttling and function stabilization are all about.

Recently, in an empty cargo management App developed by me for a domestic aviation, I simply optimized the process by using the ideas of throttling and shaking prevention.

Throttling and anti-shaking

Function throttling means that js methods run only once in a certain amount of time. For example, the human eye blinks once in a certain period of time.

Function stabilization means that when triggered frequently, the code is executed only once when there is enough idle time. Take a bus in life, for example, is a certain period of time, if someone has to swipe the card to get on the bus, the driver will not drive. A driver only drives when someone else’s card is gone.

Flutter of throttling

Function throttling, simply put, prevents a function from being called consecutively in a short interval. Only when the interval you specify has passed since the last function was executed can the function be called again.

Analyze the throttling function in the business:

class MyStatefulWidgetState extends State<OrderPageEdit> {
  bool canScanning; // Whether it can be scanned
  // Scan the control flow
  final Stream<dynamic> _barScanner =
      EventChannel('com.freshport.freshport/barcode').receiveBroadcastStream();
  StreamSubscription<dynamic> _barScannerSubscription;

  @override
  void initState() {
    super.initState();
    _barScannerSubscription = _barScanner.listen((data) {
      if(! canScanning)return;
      setState(() {
        canScanning = false;
      });
      scanning(data);
    });
  }

  @override
  void dispose() {
    _barScannerSubscription.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Widget;
  }

  // Scan
  scanning(goodsCode) async {
    final result = await fetch.fetch(url: 'www.nicai.com');
    setState(() {
      canScanning = true;
    });
    if (result.result) {
    } else{}}}Copy the code

Explain this code, because this project is to scan the bar code for goods warehousing operation, our expectation is to scan once, read from the database to complete the addition of a goods to the list. Therefore, even scanning cannot read before this. Therefore, I added a flag bit to the _barScanner listener function. This flag bit is used to determine whether flag is being read and set to true after reading. At this point you can continue scanning. Of course, my throttling function does not have an obvious unfiring time as some intercept functions do, which is the loading time.

Flutter of stabilization

The stabilization function is defined as an event handler that executes only once after the event handler is triggered multiple times, and executes at the end of the event handler. Its principle is to delay the operation of the processing function. If the event is triggered again before the set delay comes, the last delay operation timer will be cleared and the timer will be reset.

Anti – shake function is mainly used to deal with real-time search, drag and drop, login user name and password format verification. In the JS environment, we usually use the timing function setTimeout to handle the shaking. In the same way that Flutter is handled by a timing function (or delay function).

In an input field corresponding to the constant search, I used the anti-shake treatment:

class MyStatefulWidgetState extends State<GoodsCodeList> {
  // Retrieve input
  final TextEditingController _textController = TextEditingController();
  // Set the anti-shake period to 3s
  Duration durationTime = Duration(seconds: 3);
  Timer timer;

  @override
  void initState() {
    super.initState();
  }

  @override
  voiddispose() { _textController.clear(); timer? .cancel();super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return TextField(
        controller: _textController,
        decoration: InputDecoration(
            contentPadding: EdgeInsets.all(5.0),
            hintText: "Please enter the commodity code",
            prefixIcon: Icon(Icons.search, color: Colors.black),
            focusedBorder: OutlineInputBorder(
              borderSide: BorderSide(color: Colors.black),
            ),
            border:
                OutlineInputBorder(borderRadius: BorderRadius.circular(3.0))),
        onChanged: (String text) {
          // limit and throttle
          if (text.trim().length < 5) return; setState(() { timer? .cancel(); timer =new Timer(durationTime, () {
              // Search function}); }); }); }}Copy the code

As shown in the code, a Timer object is set first. When the input box TextField continues to be entered, the cancel event of the Timer object will be triggered all the time. Then, a new Timer function with a period of 3s will be assigned to the Timer. This timing function fires when no information is entered in 3s. But if you type it again in three seconds, the timing function will be cancelled again and the new timing function will be assigned a period of 3s.

So that’s the anti-shake function in action.

finishing

We often come into contact with function throttling and throttling in JS code, because DOM operations (onresize, onscroll and so on) consume the most performance in JS. However, the same event will be triggered many times in some scenes. In order to reduce operations, the concept of throttling and throttling was developed. In many cases, you can use anti-shake and throttling to reduce unnecessary operations and Ajax requests