将onClick更改为随机

Changing onClick to be random

本文关键字:随机 onClick      更新时间:2023-09-26

我希望使处理程序OnClick只是随机实例,而不需要用户交互。

// add the canvas in
  document.body.appendChild(mainCanvas);
  document.addEventListener('mouseup', createFirework, true);
  document.addEventListener('touchend', createFirework, true);
// and now we set off
    update();
  }
  /**
   * Pass through function to create a
   * new firework on touch / click
   */
  function createFirework() {
        createParticle();
  }

谢谢!:)

拥有一个函数调用本身并不太难:

// This function executes itself the first time immediately
(function randFunc () {
    // We output some information to the console
    console.log("Called myself..." + new Date());
    // And then instruct this function to be called between 0 and 10 seconds
    setTimeout(randFunc, Math.random() * 10 * 1000);
}());​​

演示:http://jsfiddle.net/8tZEu/2/

只是从Jonathan扩展一个很好的解决方案:你不需要创建eventListeners递归randFunc()在随机时间被调用,直到你退出浏览器。

我猜你需要实现一种方法来停止函数。这里有一个解决方案:

     var stopFW = false;
        function randFunc () {
             // stop execution           
            if (stopFW) return;
            console.log("Called myself..." + new Date());
            // And then instruct this function to be called between 0 and 10 seconds
            setTimeout(randFunc, Math.ceil(Math.random() * 10) * 1000);
        }
        function stopFireWork() {
            stopFW = !(stopFW);
            console.log(stopFW);
        }
<body onload="randFunc()">    
    <button onclick="stopFireWork()">Stop Firework</button>
</body>