File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ 'use strict' ;
2+
3+ const wrap = ( func ) => {
4+ let limit = 0 ;
5+ let counter = 0 ;
6+ let timer = null ;
7+ let fn = func ;
8+
9+ const wrapper = ( ...args ) => {
10+ if ( ! fn ) return ;
11+ if ( limit && counter ++ === limit ) {
12+ limit = 0 ;
13+ counter = 0 ;
14+ this . cancel ( ) ;
15+ return ;
16+ }
17+ return fn ( ...args ) ;
18+ } ;
19+
20+ const methods = {
21+ cancel ( ) {
22+ fn = null ;
23+ return this ;
24+ } ,
25+ resume ( ) {
26+ if ( ! fn ) {
27+ fn = func ;
28+ if ( limit ) {
29+ limit = 0 ;
30+ counter = 0 ;
31+ }
32+ }
33+ return this ;
34+ } ,
35+ timeout ( msec ) {
36+ if ( timer ) clearTimeout ( timer ) ;
37+ timer = setTimeout ( ( ) => this . cancel ( ) , msec ) ;
38+ return this ;
39+ } ,
40+ limit ( count ) {
41+ limit = count ;
42+ counter = 0 ;
43+ return this ;
44+ }
45+ } ;
46+
47+ return Object . assign ( wrapper , methods ) ;
48+ } ;
49+
50+ // Usage:
51+
52+ const fn = ( par ) => {
53+ console . log ( 'Function called, par: ' + par ) ;
54+ } ;
55+
56+ const f = wrap ( fn ) . timeout ( 200 ) . limit ( 3 ) ;
57+ f ( '1st' ) ;
58+
59+ setTimeout ( ( ) => {
60+ f ( '2nd' ) ;
61+ f . cancel ( ) ;
62+ f ( '3rd' ) ;
63+ f . resume ( ) ;
64+ f ( '4th' ) ;
65+ f . timeout ( 200 ) ;
66+ setTimeout ( ( ) => {
67+ f ( '5th' ) ;
68+ setTimeout ( ( ) => {
69+ f ( '6th' ) ;
70+ } , 150 ) ;
71+ } , 150 ) ;
72+ } , 150 ) ;
You can’t perform that action at this time.
0 commit comments