JSFiddle - React, Tailwind, and code Playground
by tea4two
HTML
<div id="imgSect">
<img src="http://lorempixel.com/200/200/sports/1/" alt="デフォルト猫ちゃん" id="mainImage" />
</div>
<button id="stopIntvl">スライドをストップします</button>
<button id="startIntvl">スライドを再開します</button>
JavaScript
var mainImg = document.getElementById('mainImage');
//ローテーションさせるイメージ
var imgArr = ['http://lorempixel.com/200/200/sports/1/','http://lorempixel.com/200/200/sports/2/','http://lorempixel.com/200/200/sports/3/','http://lorempixel.com/200/200/sports/4/','http://lorempixel.com/200/200/sports/5/'];
//カウンター
var imgIndex = 0;
function changeImg() {
mainImg.setAttribute('src',imgArr[imgIndex]);
imgIndex++;
if( imgIndex >= imgArr.length ) {
imgIndex = 0;
}
}
//setInterval(changeImg, 3500);//3.5秒でイメージの切り替え発生
//setInterval,setTimeoutはIDを返します。
var stopBtn = document.getElementById('stopIntvl'),
startBtn = document.getElementById('startIntvl');
var intervalHandle = setInterval(changeImg, 3500);
stopBtn.onclick = function() {
clearInterval(intervalHandle);
};
startBtn.onclick = function() {
clearInterval(intervalHandle);
intervalHandle = setInterval(changeImg, 3500);
};