简体   繁体   中英

How to solve a real time transaction problem in JavaScript?

I encounter two problems regarding the transaction which needs to be solved in JavaScript.

Let's say some transaction requests are going to happen after (2seconds, 5seconds, 6seconds, 9seconds, 12seconds, 16seconds...). I need to write a simple function that makes sure there is at least a 5sec interval between two requests and ignores others. So in this example, only transactions at 2seconds, 9seconds, and 16seconds are accepted. Another problem I had is that writing a function that only accepts a request at 0s, 5s, 10s, 15s...whatever is closer to the 5s mark and ignore others. This time, the function should accept transactions at 2sec, 5sec, 9sec, and 16sec and ignore others.

`

setTimeout(transaction(2), 2000);
setTimeout(transaction(5), 5000);
setTimeout(transaction(6), 6000);
setTimeout(transaction(9), 9000);
setTimeout(transaction(12), 12000);
setTimeout(transaction(16), 16000);
//first problem: print 2,9,16 
//second problem: print 2,5,9,16

`

I have an idea to solve these two problems using setTimeout/setInterval/Closure but I'm not sure about how I can integrate them together.

Use RxJS's debounceTime :

https://www.learnrxjs.io/operators/filtering/debouncetime.html

Discard emitted values that take less than the specified time between output

let transactions$ = getObservableForTransactions();
transactions$
    .pipe(
        debounceTime( 5000 )
    )
    .subscribe( txn => console.log( txn ) );

Demonstration

For your use-case specifically, I don't know where your "transactions" are coming from - but here's a more fleshed-out example using debounceTime :

// Step 1: Input:
let input = [
    { value:  2, delay:  2000 },
    { value:  5, delay:  5000 },
    { value:  6, delay:  6000 },
    { value:  9, delay:  9000 },
    { value: 12, delay: 12000 },
    { value: 16, delay: 16000 }
];

// Step 2: Set-up an Observable Subject:
let obs$ = new Subject<number>();

// Set-up an initial anonymous subscriber to print all values (without debouncing):
obs$.subscribe( {
    next: v => console.log( 'value emitted: %o', v );
} );

// Step 3: Set-up the debounced subscriber:
obs$.pipe( debounceTime( 5000 ) )
    .subscribe( { next: v => console.log( 'Debounced value emitted: %o', v ); } );

// Step 4: Spam `setTimeout` to trigger the process:
for( var item in input ) {
    setTimeout( () => obs$.next( item.value, item.delay );
} 

// Step 5: Open your browser console and view the results in real-time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM