Javascript 将onClick更改为随机
我希望使处理程序OnClick成为随机实例,而不需要用户交互Javascript 将onClick更改为随机,javascript,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 updat
// 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);
}());
演示:只需从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>
var stopFW=false;
函数randFunc(){
//停止执行
if(stopFW)返回;
log(“称我自己…”+新日期());
//然后指示在0到10秒之间调用此函数
setTimeout(randFunc,Math.ceil(Math.random()*10)*1000);
}
函数stopFireWork(){
stopFW=!(stopFW);
控制台日志(stopFW);
}
停止烟火
类似window.setInterval(createFirework,1000)的东西会导致“click”处理程序每秒触发一次。这与您正在寻找的类似吗?您希望以随机间隔调用createFirework
?如果是这样,最短和最长的间隔应该是什么?乔纳森·桑普森:是的,这就是我要找的。@syazdani是的!这就是我想找的。现在我该把它放在哪里,如何将间隔设置为随机的?@syazdani,就是这样!非常感谢你现在,我是JS N00B。我应该把这个放在哪里?@user1932995任何地方。。。除非它要求已经设置了其他环境变量,或者需要加载DOM。我遇到了这样的问题:(是这样的吗?(函数createFirework(){createParticle());setTimeout(randFunc,Math.ceil(Math.random()*10*1000));}());@对setTimeout
的单间隔调用应包含对要调用的函数的引用。您仍然拥有randFunc
,即使您将该函数的名称更改为createFirework
。你到底想做什么?