나는 슬라이더 라이브러리를 사용하고 있으며, 실제로 객체 (모듈 패턴 사용)를 한 번 사용할 수 있다는 사실에 대해 혼란 스럽다. 내가 당신을 보여 드리죠 :setInterval이 내 스크립트를 차단하고 있습니까?
let PapaSlide = (function(d) {
'use strict';
let _options = {}, _container, _items, _actIndex, _prevIndex;
let _setOptions = function(opt) {
return {
container: opt.container || 'papa-container',
items: opt.items || 'papa-item',
transitionDuration: opt.transitionDuration || '300',
transitionFunction: opt.transitionFunction || 'ease-in',
timeInterval: opt.timeInterval || '3000',
animationType: opt.animationType || 'fade',
type: opt.type || 'auto',
startAt: opt.startAt || 0
}
};
let _setIndexes = function() {
_options.startAt = _options.startAt > _items.length - 1 ? 0 : _options.startAt;
_actIndex = _options.startAt;
_prevIndex = (_actIndex === 0) ? _items.length - 1 : _actIndex - 1;
};
let _addTransitionStyle = function() {
_items.forEach(item => {
item.style.transitionDuration = `${_options.transitionDuration}ms`;
item.style.transitionTimingFunction = _options.transitionFunction;
});
};
let _sliderType = function() {
_setIndexes();
if(_options.animationType === 'fade' && _options.type === 'auto') {
_autoFade();
}
};
let _autoFade = function() {
_items[_actIndex].style.opacity = 1;
setInterval(() => { // is this blocking my other sliders?
_prevIndex = _actIndex;
_actIndex++;
if(_actIndex > _items.length - 1) {
_actIndex = 0;
}
_items[_prevIndex].style.opacity = 0;
_items[_actIndex].style.opacity = 1;
}, parseInt(_options.timeInterval));
};
let setPapaSlider = function(opt) {
_options = _setOptions(opt);
_container = d.getElementsByClassName(_options.container)[0];
if(_container) {
_items = Array.prototype.slice.call(_container.getElementsByClassName(_options.items));
if(_items.length > 0) {
_addTransitionStyle();
_sliderType();
}
else {
console.error('Items have been not found');
}
}
else {
console.error('Container has been not found');
}
};
return {
setPapaSlider: setPapaSlider
}
})(document);
내 main.js 사실
(function(PapaSlide) {
"use strict";
PapaSlide.setPapaSlider({container: 'fade-auto', timeInterval: '1200'});
PapaSlide.setPapaSlider({container: 'fade-self', timeInterval: '2000'});
})(PapaSlide || {});
를, '페이드 자체를'클래스 단지 컨테이너는 정지 '페이드 자동', 슬라이딩된다. 이것은 자바 스크립트가 하나의 스레드를 가지고 있기 때문에 setInterval이 다른 PapaSlide 액션을 차단하고 있기 때문입니까? 나는 콘솔 옵션에서 콘솔을 사용했고 옵션에 인수를 입력 했으므로 ...? clearInterval 어딘가 사용해야합니까? 하지만이 슬라이더는 부정사 적이기 때문에 나는 그럴 수 없다고 생각합니다.
편집
확인. 나는 이런 것을했다. IFFE 함수에서 삭제했습니다. 그냥 입력 :
let fade1 = new PapaSlide();
fade1.setPapaSlide({container: 'fade-auto'});
let fade2 = new PapaSlide();
fade2.setPapaSlide({container: 'fade-self'});
이 좋은 해결책이 있습니까?
내가 작성한 원래 함수가 실패한 이유에 대한 답을 썼습니다. 귀하의 편집은 확실히 문제를 해결할 것입니다. 즉, 당신은'document' 변수로'PapaSlide()'를 호출한다고 가정하고 있습니다. 둘째, PapaSlider는 [생성자]가 아니기 때문에 new 연산자가 필요 없습니다 (http : /bonsaiden.github.io/JavaScript-Garden/#function.constructors) – javinor
es6로 작성 했습니까? – sabithpocker