2012-05-01 16 views
11

Secondo il underscore documentation:underscore.js: _.throttle (funzione attendere)

throttle_.throttle (funzione, attendere)
crea e restituisce una nuova, strozzati versione della funzione passata , che, quando viene invocato ripetutamente il numero , chiamerà solo la funzione originale al massimo una volta per ogni millisecondo di attesa. Utile per eventi limitatori di velocità che si verificano più velocemente di quanto tu possa tenere il passo con.

Che cosa significa Useful for rate-limiting events that occur faster than you can keep up with.
Questa funzione è equivalente a setTimeout con una funzione che chiama se stessa?
Qualcuno può fornirmi qualche esempio su jsfiddle?

+1

È utile per esempio. per scorrere o ridimensionare i gestori di eventi che altrimenti vengono attivati ​​spesso per la maggior parte degli scopi durante lo scorrimento o il ridimensionamento della finestra. – Niko

risposta

7

è non solo setTimeout() Prova questa

var a = _.throttle(function(){console.log('called')}, 1000); 
while(true) { 
    a(); 
} 

verrà chiamato una volta al secondo e non una volta ogni iterazione. In JS nativi sarebbe simile:

var i = null; 
function throttle(func, delay){ 
    if (i) { 
     window.clearTimeout(i); 
    } 
    i = window.setTimeout(func, delay) 
} 
non

esattamente lo stesso, ma solo per illustrare che la funzione viene chiamata una volta

+0

Non si dovrebbe usare 'while (true)' – andlrc

+6

Ciò è 'debounce', non' throttle', poiché non scatterà mai fino a quando viene chiamato prima che il timer sia stato cancellato. – vsync

4

Per estendere Darhazer's answer

E 'più simile, ad eccezione _.throttle si chiama imminente e poi di nuovo dopo delay millisecondi

function throttle(func, delay) { 
    var timer = 0; 

    return function() { 
     var context = this, 
      args = [].slice.call(arguments); 

     clearTimeout(timer); 
     timer = setTimeout(function() { 
      func.apply(context, args); 
     }, delay); 
    }; 
} 
+3

Questa è anche una funzione 'debounce' ... non una' throttle'. http: // drupalmotion.it/article/debounce-and-throttle-visual-explanation – vsync

1

ho trovato questo eccellente jsfiddle che hel Mi ped:

http://jsfiddle.net/amyseqmedia/dD99u/37/

Nel mio caso avevo bisogno di acceleratore perché una funzione (che era una richiesta del server) è stato chiamato circa 500 volte in 1 secondo, ed è stato sovraccaricare il server. Quindi l'ho modificato in modo che la funzione potesse essere chiamata max una volta per 3 secondi. Quindi non importa quante volte viene chiamato, si verifica solo una volta ogni 3 secondi al massimo.

Qualcosa di simile:

var informationFromServer; 
var a = _.throttle(function(){ 
    informationFromServer = serverCallFunction(); 
}, 3000); 

function getsCalledALot() 
{ 
    a(); 
} 

function serverCallFunction() 
{ 
    var data = $.post.... 
    return data; 
} 
+0

concordato, http://jsfiddle.net/amyseqmedia/dD99u/37/ è eccellente! – jbobbins

+0

il violino non funziona più. –

1

La differenza tra acceleratore e antirimbalzo é descritto qui: https://css-tricks.com/the-difference-between-throttling-and-debouncing/

/* 
"Debouncing enforces that a function not be called again until a certain amount of time has passed without it being called. As in "execute this function only if 100 milliseconds have passed without it being called." 
"Perhaps a function is called 1,000 times in a quick burst, dispersed over 3 seconds, then stops being called. If you have debounced it at 100 milliseconds, the function will only fire once, at 3.1 seconds, once the burst is over. Each time the function is called during the burst it resets the debouncing timer." 
*/ 
_.debounce = (fn, delay) => { 
    let timer 
    return (...args) => { 
    if (timer) clearTimeout(timer) 
    timer = setTimeout(() => { 
     fn.apply(null, args) 
    }, delay) 
    } 
} 
/* 
"Throttling enforces a maximum number of times a function can be called over time. As in "execute this function at most once every 100 milliseconds." 
*/ 
_.throttle = (fn, delay) => { 
    let canCall = true 
    return (...args) => { 
    if (canCall) { 
     fn.apply(null, args) 
     canCall = false 
     setTimeout(() => { 
     canCall = true 
     }, delay) 
    } 
    } 
} 
0

_.throttle viene utilizzato per impedire frequenti chiamate su un metodo di particolare ms.Fai una immagine per capire questo RestrictfrequentCall.jpg

Problemi correlati