下面的代码是一个页面数组,它被洗牌,然后每个页面都在iframe中显示一段时间。我希望能够使用按钮或鼠标单击启动/停止pageChange
功能。谁能帮我这个?下面是工作代码,或者检查这个小提琴:http://jsfiddle.net/xaa1qccm/(感谢Nobe4)
var pages=[];
pages[0]="http://example.com/";
pages[1]="http://www.iana.org/domains/reserved";
pages[2]="http://en.wikipedia.org/wiki/Main_Page";
pages[3]="http://en.wikipedia.org/wiki/Randomness";
var shuffle = function(array){
var shuffledPages = [];
while(array.length){
shuffledPages.push(array.splice(Math.floor(array.length*Math.random()),1));
}
return shuffledPages;
}
var time = 3300;
var currentIndex = 0;
function pageChange() {
if(currentIndex == 0){
pages = shuffle(pages);
console.log(pages);
currentIndex = pages.length;
}
currentIndex--;
document.getElementById("frame").src=pages[currentIndex];
console.log(currentIndex);
setTimeout(function() { pageChange(); }, time);
};
pageChange();
答案 0 :(得分:0)
您可以添加一个开始/停止变量,以便检查状态:
[...]
var time = 3300;
var currentIndex = 0;
var stop = 0;
function pageChange() {
if(currentIndex == 0){
pages = shuffle(pages);
console.log(pages);
currentIndex = pages.length;
}
if (stop == 0)
{
currentIndex--;
document.getElementById("frame").src=pages[currentIndex];
console.log(currentIndex);
setTimeout(function() { pageChange(); }, time);
}
};
function startStop()
{
if (stop == 0){
stop = 1;
}
else{
stop = 0;
pageChange();
}
}
[...]
然后在所需按钮的点击事件上调用startStop()
修改:这是jsfiddle
答案 1 :(得分:0)
一个变量,可以设置为确定旋转器是否正在运行,并将其设置为true或false:
var isRunning = true;
....
<button onclick="isRunning = false">stop</button>
<button onclick="isRunning = true">start</button>
并检查方法内部:
function pageChange() {
if(isRunning){
...
}
setTimeout(function() { pageChange(); }, time);
};