SetInterval, no se puede asignar a una variable

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?

preguntado el 12 de febrero de 14 a las 08:02

You immediately clear the interval you've set... -

When do you want to remove the interval ? What you try to do isn't clear. -

It doesn't work because you clear interval before they running. Put clearinterval into timeout or callback. -

Put the clearInterval(check_timer) inside the setTimeout and you'll see it will continue for 5 seconds -

owned by javascript's async nature^^ -

1 Respuestas

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 or haz tu propia pregunta.