Etienne Etienne - 14 days ago 6
HTML Question

JavaScript Page Rotate with Pause/Play

Please note it can ONLY be JavaScript. Please see below my current HTML.
I need to rotate between pages as the code currently does. BUT, I need to be able to pause/play between the pages.



<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>

<iframe id="rotator" src="http://www.example.com" onload="this.width=1000;this.height=750;"></iframe>

<script>
// start when the page is loaded
window.onload = function () {

var urls = [
"http://www.example.com",
"http://www.example2.com",
// ....
"http://www.example3.com"
];

var index = 1;
var el = document.getElementById("rotator");

setTimeout(function rotate() {

if (index === urls.length) {
index = 0;
}

el.src = urls[index];
index = index + 1;

// continue rotating iframes
setTimeout(rotate, 15000);

}, 15000); // 5000ms = 5s
};
</script>


</body>
</html>




Answer

use setInterval and clearInterval method as like this below

var run;
var el =document.getElementById('rotator');
var urls = [
                  "http://www.example.com",
                  "http://www.example2.com",
                 
                  "http://www.example3.com"
                ];
(function()
 {
  run = setInterval(rotate , 1000)
  console.log('start')
})()

var index=0;
function rotate(){
if (index === urls.length) {
                        index = 0;
                    }
                 el.src = urls[index];
                    index ++;
                                }

function pause(){
clearInterval(run);
  console.log('pause')
}
function play(){
run = setInterval(rotate , 1000);
  console.log('play');
}
<iframe id="rotator" src="http://www.example.com" ></iframe>  
<button onclick="pause()">
pause
</button>
<button onclick="play()">
play
</button>

Comments