0
所以我有一個圖像,我想淡出,替換,然後淡入。我不想打擾與jQuery這樣一個小任務,所以我發現了一個js淡入淡出功能,並將其修改爲我喜歡。如何在不破壞函數的情況下暫停執行setTimeout調用?
起初,我的代碼很簡單:
setTimeout(function(){fadeOut(id, val);},300);
set_slide(s1, current);
setTimeout(function(){fadeIn(id, val);},300);
我很快意識到,這並不工作,因爲set_slide(args)
和其他setTimeout(args)
將被立即調用,而不是阻塞,直到第一setTimeout(args)
運行完成。
這迫使我做的東西很醜陋和鏈我的代碼在一起,使得第二2函數調用,set_slide(args) and setTimeout(args)
,被稱爲內fadeOut
和我的第一setTimout成爲
setTimeout(function(){
fadeOut(s1,slide_1,current,9);
},300);
完整的腳本:
var previous = 0; //will hold index of image directly before the current image
var current = 1; //will hold the index of the current image
var next = 2; //will hold the index of the image directly after the current image
var images = [];
var s1 = document.getElementById('slide1');
var s2 = document.getElementById('slide2');
var s3 = document.getElementById('slide3');
var slide_1 = document.getElementById('slide1-img');
var slide_2 = document.getElementById('slide2-img');
var slide_3 = document.getElementById('slide3-img');
s2.addEventListener("click", moveBackward);//enable move forward image button
s3.addEventListener("click", moveForward);//enable move backwards image button
<?php
//output each image src into an array
$photoCount=count($aboutGallery);
foreach ($aboutGallery as $photo){
echo 'images.push("'.$photo['full_url'].'");';
}
?>
var lengthImg = images.length;
function moveForward(){
//each of these calls increases the index reference by 1 while looping
//around when the end of the array is reached
previous = (current)%(lengthImg);
current = (current+1)%(lengthImg);
next = (current+1)%(lengthImg);
//set current slide
setTimeout(function(){
fadeOut(s1,slide_1,current,9);
},300);
//set previous and next slides
setTimeout(function(){
fadeOut(s2,slide_2,previous,9);
fadeOut(s3,slide_3,next,9);
},300);
}
function setSlide(container, slideNum){
container.src = images[slideNum];
if(document.readyState === 'complete'){//ensures scripts.js has been loaded and doesn't run on first load
setBackgroundImage();
}
}
function fadeOut(id,slide,position,val){
if(isNaN(val)){ val = 9;}
id.style.opacity='0.'+val;
//For IE
id.style.filter='alpha(opacity='+val+'0)';
if(val>0){
val--;
console.log(position);
setTimeout(function(){fadeOut(id,slide,position,val)},50);
}else{
//input next slide and fade in
setSlide(slide, position);
fadeIn(id,9);
return;}
}
是你的「醜陋」的鏈接後工作? –
是的,它有效,但有沒有辦法暫停腳本的執行 –
沒有這樣的事情在js中暫停,因爲該語言是單線程的。但是,您可以取消setTimeout。爲此,你需要存儲一個引用'var timerReference = setTimeout(myFunction,1000);'你可以隨時通過調用'clearTimeout(timerReference)'來取消超時;' –