改变onClick是随机的

时间:2012-12-27 20:11:25

标签: javascript

我希望使处理程序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();
  }

谢谢! :)

2 个答案:

答案 0 :(得分:0)

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

// 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/

答案 1 :(得分:0)

只需从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>