2015-03-12 18 views
9

creo una versione adattato dal di una funzione con sottolineatura:Come cancellare una funzione rimossa dopo che è stata chiamata e prima che venga eseguita?

var debouncedThing = _.debounce(thing, 1000); 

volta debouncedThing si chiama ...

debouncedThing(); 

... c'è un modo per annullarla, durante il periodo di attesa prima effettivamente esegue?

+0

Perché il downvote? – user1031947

+0

possibile duplicato di [Utilizzo della funzione di rimbalzo nel trattino basso] (http://stackoverflow.com/questions/7026000/using-debounce-function-in-underscore) –

+0

Questa domanda non è chiara. Il mio è specifico. Quella domanda non fornisce una risposta alla mia domanda. – user1031947

risposta

1

Quello che ho fatto è usato _.mixin per creare un metodo _.cancellableDebounce. È quasi identico all'originale ad eccezione di due nuove linee.

_.mixin({ 
    cancellableDebounce: function(func, wait, immediate) { 
     var timeout, args, context, timestamp, result; 

     var later = function() { 
      var last = _.now() - timestamp; 

      if (last < wait && last >= 0) { 
      timeout = setTimeout(later, wait - last); 
      } else { 
      timeout = null; 
      if (!immediate) { 
       result = func.apply(context, args); 
       if (!timeout) context = args = null; 
      } 
      } 
     }; 

     return function() { 
      context = this; 
      args = arguments; 
      timestamp = _.now(); 
      var callNow = immediate && !timeout; 
      if (!timeout) timeout = setTimeout(later, wait); 
      if (callNow) { 
      result = func.apply(context, args); 
      context = args = null; 
      } 

      // Return timeout so debounced function can be cancelled 
      result = result || {}; 
      result.timeout = timeout; 

      return result; 
     }; 
    } 
}); 

USO:

var thing = function() { 
    console.log("hello world"); 
} 

var debouncedThing = _.cancellableDebounce(thing, 1000); 
var timeout = debouncedThing().timeout; 

clearTimeout(timeout); 
0

Il modo più semplice per cancellare un già detta funzione entro il suo periodo di antirimbalzo è quello di rendere annullabile. In realtà basta aggiungere 3 righe di codice e una condizione.

const doTheThingAfterADelay = debounce((filter, abort) => { 
    if (abort) return 

    // here goes your code... 

}, /*debounce delay*/500) 


function onFilterChange(filter) { 
    let abort = false 

    if (filter.length < 3) { // your abort condition 
    abort = true 
    } 

    doTheThingAfterADelay(filter, abort) // debounced call 
} 

Si annulla richiamandolo di nuovo con abort = true.

Per avere un riferimento, questo è il vostro classico debounce funzione preso da Underscore. Rimane intatto nel mio esempio.

// taken from Underscore.js 
// Returns a function, that, as long as it continues to be invoked, will not 
// be triggered. The function will be called after it stops being called for 
// N milliseconds. If `immediate` is passed, trigger the function on the 
// leading edge, instead of the trailing. 
export function debounce(func, wait, immediate) { 
    let timeout 
    return function() { 
    let context = this, args = arguments 
    let later = function() { 
     timeout = null 
     if (!immediate) func.apply(context, args) 
    } 
    let callNow = immediate && !timeout 
    clearTimeout(timeout) 
    timeout = setTimeout(later, wait) 
    if (callNow) func.apply(context, args) 
    } 
} 
10

Se si utilizza l'ultima versione di lodash si può semplicemente fare:

// create debounce 
const debouncedThing = _.debounce(thing, 1000); 

// execute debounce, it will wait one second before executing thing 
debouncedThing(); 

// will cancel the execution of thing if executed before 1 second 
debouncedThing.cancel() 

Un'altra soluzione è quella con una bandiera:

// create the flag 
let executeThing = true; 

const thing =() => { 
    // use flag to allow execution cancelling 
    if (!executeThing) return false; 
    ... 
}; 

// create debounce 
const debouncedThing = _.debounce(thing, 1000); 

// execute debounce, it will wait one second before executing thing 
debouncedThing(); 

// it will prevent to execute thing content 
executeThing = false; 
Problemi correlati