如何设置触发对象的延迟

How to set a delay for firing an object

我在下面有一个代码,一旦按下按钮(基于不同的假设),它就会将一个对象触发到我创建的 canvas 上。但是,我希望在按下按钮和将对象发射到 canvas 之间有 5 秒的延迟,我只是不确定在我的代码中输入它的位置。

我假设我需要一个 setTimeout 函数,但不确定。我知道下面的代码目前不会做任何事情,但是谁能告诉我我需要在代码中的什么地方放置 setTimeout 函数。我试了很多地方都没有用。

谢谢。

 trigger = function() {
    reset();

    var effect_size = .8;

    localStorage.setItem("value mac", document.getElementById('demo'));
    localStorage.setItem("direction", direction);

    //var y = document.getElementById("myCanvas")
    //const context = y.getContext('2d');
    //context.clearRect(0, 0, y.width, y.height);
    console.log(direction);
    
    console.log ('check????')

    var y = document.getElementById("myCanvas");
    var cir = y.getContext("2d");
    var value_global = document.getElementById('myRange').value;

    console. log(value_global)
    var min_val = (value_global > 1) * ((value_global-1)*.1 - .05);
    if(value_global>1 && value_global<9){
        var range_val = 0.3;
    }else if(value_global==1 || value_global==9){
        var range_val = 0.25;
    }else{
        var range_val = 0.15;
    }
    
    if (direction === 'east') {
      var cen_x = 480-150*value_global/100;
      var cen_y = 300;
      min_val = min_val * effect_size;
    }else if(direction === 'north'){
      var cen_x = 300;
      var cen_y = 70+200*value_global/100;
      min_val = min_val * .2;
    }else if(direction === 'west'){
      var cen_x = 240-150*value_global/100;
      var cen_y = 300;
      min_val = min_val * .2;
    }else if(direction === 'south'){
      var cen_x = 300;
      var cen_y = 322+200*value_global/100;
      min_val = min_val * .2;
    }else{
      alert("Error: Invalid direction.")
    }
    
    cir.globalAlpha = Math.random()*range_val + min_val;

    console.log(cir.globalAlpha)
    
    cir.beginPath();
    cir.arc(cen_x, cen_y, 20, 0, 2 * Math.PI);
 
    cir.fillStyle = "red";
    cir.fill();
    cir.stroke();

  }

需要延迟的代码部分应包装在 setTimeout 函数回调中,这样:

setTimeout(function() {
    cir.beginPath();
    cir.arc(cen_x, cen_y, 20, 0, 2 * Math.PI);

    cir.fillStyle = "red";
    cir.fill();
    cir.stroke();
}, 5000)

如果按钮被点击两次,那么该函数将被执行两次。如果你想避免这种情况(即只运行最后一次超时),那么timeoutID需要存储在一个全局变量中,并且必须在再次调用setTimeout之前调用clearTimeout

let timeoutID

trigger = function() {

    /* ... rest of the code here... */

    if (timeoutID)
        clearTimeout(timeoutID)

    timeoutID = setTimeout(function() {
        cir.beginPath();
        cir.arc(cen_x, cen_y, 20, 0, 2 * Math.PI);

        cir.fillStyle = "red";
        cir.fill();
        cir.stroke();
    }, 5000)

}