当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - Repeating a function in regular intervals

问题描述:

 setInterval(function(){

setTimeout(function(){

$('#a').addClass('x');

},1000);

setTimeout(function(){

$('#a').removeClass('x');

},2000);

},4000);

I was trying to add the class "x" to the div "#a" after 1 s & remove the class after 2 s & repeat the entire function as a loop which executes every 3 s.But the loop worked only once as the time in the setTimeout function did not get incremented after 3 s .So can you help me to make this working.

网友答案:

you have incorrect syntax. also, this can be done without timeouts, just to give you a brief idea:

setInterval(function(){
   $("#a").addClass("x").delay(1000).queue(function(next){
     $(this).removeClass("x");
     next();
   });
},6000);

See it in a fiddle

网友答案:

You have incorrect syntax while setting the interval in both setTimeout and setInterval methods:

setInterval(function(){
   setTimeout(function(){
       $('#a').addClass('x');
   },1000);
   setTimeout(function(){
       $('#a').removeClass('x');
   },2000);
},4000);
网友答案:

I think you want to add class x for 1 sec and remove it after another sec. You can set the interval to 1 sec and check and remove if element has class otherwise add it.

Below code should work for your prob. you can add a delay of 1 sec if required keeping loop count.

setInterval( function(){
       if( $('#a').hasClass('x')){
            $('#a').removeClass('x');
        } else {
            $('#a').addClass('x');
        }
 },1000);
网友答案:

You have to wtite time period within bracket which corrected in below code.

setInterval(function(){
       setTimeout(function(){
           $('#a').addClass('x');
       },1000);
       setTimeout(function(){
           $('#a').removeClass('x');
       },2000);
   },4000);

DEMO

分享给朋友:
您可能感兴趣的文章:
随机阅读: