-1

I want to use setTimeout in setInterval. First time it print out_k:0. After the interval, it prints out_k:1, inside_k:0? I don't understand, I think the inside_k should be 1. The ouside k was 1, its so strange.

     var i = 0;
     var timer = setInterval(function(){
        if(i < arr.length){
            var k=i;
            //console.log("out_i:"+i);
            console.log("out_k:"+k);                
            setTimeout(function(){
                //console.log("inside_i:"+i);
                console.log("inside_k:"+k);
            },500);
            i++;
        }else {
            clearInterval(timer);
        }   
    },500);
1
  • what is arr.length? Commented Apr 9, 2017 at 14:43

1 Answer 1

1

This is the sequence of events during the execution of your code

1) It queued up the first instance of setInterval to be executed after 500ms

2) After 500ms, it queues up second instance of setInterval and executes first instance of setInterval and prints out_k0. It also queues up setTimeout to be executed after 500ms as well when the value of k was still 0.

3) After 500ms, it queues up third instance of setInterval and executes second instance of setInterval and prints out_k1 since value of k is 1 now, but first instance of setTimeout is also executed with inside_k0

and so on.

Sign up to request clarification or add additional context in comments.

1 Comment

You mean setTimeout got the value of k when it queues up?But if I change k to i,it got the the value of i when executed .

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.