Ejecute la función una vez por evento con jQuery
-
11-09-2019 - |
Pregunta
Estoy usando jQuery para escuchar el evento DOMSubtreeModified y luego ejecutar una función.Lo que necesito es una forma de ejecutar una función solo una vez por ráfaga de evento.Entonces, en este caso, el evento solo se ejecutará después de 1 segundo y nuevamente después de 3 segundos.¿Cuál es la mejor manera de hacer esto?
jQuery
$(function(){
setTimeout(function(){
$('#container')[0].innerHTML = 'test';
$('#container')[0].innerHTML = 'test';
$('#container')[0].innerHTML = 'test';
$('#container')[0].innerHTML = 'test';
$('#container')[0].innerHTML = 'test';
$('#container')[0].innerHTML = 'test';
},1000);
setTimeout(function(){
$('#container')[0].innerHTML = 'test';
$('#container')[0].innerHTML = 'test';
$('#container')[0].innerHTML = 'test';
$('#container')[0].innerHTML = 'test';
$('#container')[0].innerHTML = 'test';
$('#container')[0].innerHTML = 'test';
},3000);
$('#container').bind('DOMSubtreeModified',function(){
console.log('event');
functionToRun();
});
});
HTML
<div id="container"></div>
Actualizar
La función setTimeout está ahí solo para emular mi problema.Necesito una solución sin cambiar el código setTimeout.El problema que tengo es que recibo una ráfaga de eventos DOMSubtreeModified y solo necesito obtener uno por ráfaga.
Solución 2
lo resolvió a mí mismo.
$(function(){
setTimeout(function(){
$('#container')[0].innerHTML = 'test';
$('#container')[0].innerHTML = 'test';
$('#container')[0].innerHTML = 'test';
$('#container')[0].innerHTML = 'test';
$('#container')[0].innerHTML = 'test';
$('#container')[0].innerHTML = 'test';
},1000);
setTimeout(function(){
$('#container')[0].innerHTML = 'test';
$('#container')[0].innerHTML = 'test';
$('#container')[0].innerHTML = 'test';
$('#container')[0].innerHTML = 'test';
$('#container')[0].innerHTML = 'test';
$('#container')[0].innerHTML = 'test';
},1100);
setTimeout(function(){
$('#container')[0].innerHTML = 'test';
$('#container')[0].innerHTML = 'test';
$('#container')[0].innerHTML = 'test';
$('#container')[0].innerHTML = 'test';
$('#container')[0].innerHTML = 'test';
$('#container')[0].innerHTML = 'test';
},3000);
addDivListener();
});
function addDivListener() {
$('#container').bind('DOMSubtreeModified',function(){
functionToRun();
$(this).unbind('DOMSubtreeModified');
setTimeout(addDivListener,10);
});
}
function functionToRun(){
console.log('event');
}
Esto muestra evento 3 veces en la consola de Firebug, y es exacta hasta 100 ms.
Otros consejos
método alternativo, que se controlar la velocidad de cualquier función.
// Control the call rate of a function.
// Note that this version makes no attempt to handle parameters
// It always induces a delay, which makes the state tracking much easier.
// This makes it only useful for small time periods, however.
// Just clearing a flag after the timeout won't work, because we want
// to do the the routine at least once if was called during the wait period.
throttle = function(call, timeout) {
var my = function() {
if (!my.handle) {
my.handle = setTimeout(my.rightNow, timeout);
}
};
my.rightNow = function() {
if (my.handle) {
clearTimeout(my.handle);
my.handle = null;
}
call();
};
return my;
};
trate de usar gestor de one()
Esto parece ser lo que estás buscando:
$(
function()
{
setTimeout
(
StartWatching,
1000
);
}
);
function StartWatching()
{
$('#container')
.bind(
'DOMSubtreeModified',
function()
{
console.log('event');
StopWatchingAndStartAgainLater();
}
);
}
function StopWatching()
{
$('#container')
.unbind('DOMSubtreeModified');
}
function StopWatchingAndStartAgainLater()
{
StopWatching();
setTimeout
(
StartWatching,
3000
);
}
Esto hace cumplir el siguiente flujo:
Document.Ready
Create DOM watching event after one second
On event, turn off event and recreate it after three seconds, rinse, repeat