简体   繁体   中英

Problems when using setTimeout in setInterval

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);

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM