SetInterval, no se puede asignar a una variable
Frecuentes
Visto 1,616 equipos
-3
Mi código es así:
$(
function(){
$("#btn").click(
function()
{
var check_timer = setInterval(
function(){
console.log("here");
...
},
1000
);
setTimeout(
function(){
console.log("set timeout");
},
5000
);
clearInterval(check_timer);
});
}
)
so here is the question, the script won't execute the function I defined in the setInterval function, unless I remove the "var check_timer", it works fine like this:
setInterval(
function(){
console.log("here");
...
},
1000
);
since I want to stop the job after some time, I use a clearInterval function, so I need to get the timer started by setInterval, how to fix this?
1 Respuestas
2
It does not execute the function becouse you clear interval before running. When you put a setTimeout
code is not "pausing". Code will continue execution and just after the timeout passes will execute and the code in setTimeout
Tratar:
$(
function(){
$("#btn").click(
function()
{
var check_timer = setInterval(
function(){
console.log("here");
...
},
1000
);
/*...*/
// instead of directly clearing the timeout
setTimeout(
function(){
// clear it after a certain amount of time
clearInterval(check_timer);
},
5000
);
});
}
)
Respondido 12 Feb 14, 08:02
No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas javascript setinterval or haz tu propia pregunta.
You immediately clear the interval you've set... - Denys Séguret
When do you want to remove the interval ? What you try to do isn't clear. - Denys Séguret
It doesn't work because you clear interval before they running. Put clearinterval into timeout or callback. - Farkhat Mikhalko
Put the clearInterval(check_timer) inside the setTimeout and you'll see it will continue for 5 seconds - Anton
owned by javascript's async nature^^ - Christoph