[英]How do I add a pause function to this pageChange timer?
代碼下面是經過改組的頁面數組,然后每個頁面在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();
您可以添加一個開始/停止變量以檢查狀態:
[...]
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();
}
}
[...]
然后,在所需按鈕的click事件上調用startStop()
編輯:這是一個jsfiddle
可以將其設置為確定旋轉器是否正在運行並將其設置為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);
};
實時示例: http : //jsfiddle.net/xaa1qccm/1/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.