Home  >  Q&A  >  body text

js setInterval problem

There are two functions a() and b(). I want to execute a first, then execute b after three seconds, then execute a after three seconds, and then execute b after three seconds, and it goes on like this.. How should I write it?

大家讲道理大家讲道理2732 days ago627

reply all(4)I'll reply

  • 怪我咯

    怪我咯2017-05-19 10:46:25

    function a() {
        setTimeout(b, 3000);
        console.info('This is a!');
    }
    function b() {
        setTimeout(a, 3000);
        console.info('This is b!');
    }
    a();

    reply
    0
  • PHP中文网

    PHP中文网2017-05-19 10:46:25

    function start() {
        a()
    }
    var timer;
    function a() {
        clearTimeout(timer);
        timer = setTimeout(b, 3000);
    }
    function b() {
        clearTimeout(timer);
        timer = setTimeout(a, 3000);
    }

    reply
    0
  • 習慣沉默

    習慣沉默2017-05-19 10:46:25

    a and b are executed every six seconds, a is executed first, and b is executed every three seconds. . . Otherwise, if the function execution time is taken into account, the three seconds interval is not the exact three seconds

    reply
    0
  • 为情所困

    为情所困2017-05-19 10:46:25

    var flag = true;
    var s = setInterval(function(){
        if(flag){
            a();
            
        }else{
            b()
        }
        flag =!flag
    
    },3000)

    reply
    0
  • Cancelreply