debounce

package module
v1.0.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 8, 2023 License: Apache-2.0 Imports: 2 Imported by: 3

README

debouncer

Debouncer ensures a method call will not be executed too frequently. Debouncer only call the callback function after a given time without new bounce event, or the time after the previous execution reaches the max duration.

Usage

package main

import (
	"fmt"
	"github.com/zhaohuabing/debounce"
	"time"
)
func main() {
	startTime:=time.Now()
	callback := func() {
		duration:=time.Since(startTime)
		startTime=time.Now()
		fmt.Printf("duration: %v\n",duration)
	}
	stop := make(chan struct{})
	d := debounce.New(200*time.Millisecond, 1*time.Second, callback, stop)
	for i := 0; i < 50; i++ {
		time.Sleep(100 * time.Millisecond)
		d.Bounce()
		if i== 10{
			d.Cancel()
		}
	}
	stop <- struct{}{}
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Debouncer

type Debouncer struct {
	// contains filtered or unexported fields
}

Debouncer ensures the callback function is not executed too frequently. Debouncer only call the callback function after a given time without new bounce event, or the time after the previous execution reaches the max duration.

func New

func New(debounceAfter, debounceMax time.Duration, callback func(), stop <-chan struct{}) *Debouncer

NewDebouncer create a Debouncer. The callback function will be called after Bounce function stops being called for debounceAfter, or the total duration reaches debounceMax. A event sent to stop channel will stop the Debouncer. Callback will be called in the go routine of the Debouncer, so make sure any resources used in the Callback to be thread-safe.

func (*Debouncer) Bounce

func (d *Debouncer) Bounce()

Bounce results a new bounce event Cancel status will be cleared after this function is called

func (*Debouncer) Cancel

func (d *Debouncer) Cancel()

Cancel the next callback The cancel status will be cleared if there is a new bounce event after being canceled

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL