1、对象构造函数
设置节点与人名
constructor({ printElement, startElement, stopElement , person }) {
this.list = person;
this.printElement = printElement;
this.startElement = startElement;
this.stopElement = stopElement;
this.interval = null;
this.time = 100;
}
2、生成随机对象
/**
* 随机人名
*/
random(){
// 获取区间范围内的数据
let num = Math.floor(Math.random() * this.list.length);
return this.list[num]
}
3、开始事件
/**
* 开始
*/
start() {
let [startNode, printNode, index] = [
document.getElementById(this.startElement),
document.getElementById(this.printElement)
]
startNode.addEventListener("click", (event) => {
this.interval = setInterval((event) => {
printNode.textContent = this.random();
}, this.time, printNode);
}, false);
}
4、结束事件
/**
* 停止
*/
stop() {
let node = document.getElementById(this.stopElement);
node.addEventListener('click', (event) => {
clearInterval(this.interval);
}, false);
}
代码下载地址:https://pan.baidu.com/s/1DgOWML9OoOoA2fiddeYCTQ