Javascript setTimeout function

前端 未结 6 1231
长发绾君心
长发绾君心 2021-01-14 11:56

I am calling this function

function drawLayers() {

    //setTimeout(drawBlueSky,500);
    //setTimeout(drawCircle1,1250);
    setTimeout(drawMoon,800);
             


        
6条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-14 12:44

    The common way to do this is using clearTimeout:

    var myTimeout = setTimeout(function(){
        alert('hi');
    }, 500);
    clearTimeout(myTimeout); // No 'hi' alert for you, sir
    

    But in your case, I would propose a more concise way of controlling all the timeouts:

    var keepRunning = true;
    
    var timeouts = {
        drawMoon: 800,
        drawCircle1: 2300,
        drawCircle2: 2700,
        drawCircle3: 3100,
        drawCircle4: 3500
        // etc...
    };
    
    for(var func in timeouts)
        var timeout = setTimeout(func, timeouts[func]);
    
    // just demonstrating a timeout run function here, such as "drawMoon":
    var drawMoon = function(){
        ...
        if(!keepRunning)
            return;
        ...
        // probably conditionally
        keepRunning = false;
        ...
    };
    

提交回复
热议问题