자바 스크립트에서 시간 지연을 설정하는 방법
이미지를 전환하기 위해 웹 사이트에 js가 있지만 이미지를 두 번 클릭하면 지연이 필요합니다. 지연은 1000ms 여야합니다. 따라서 img.jpg를 클릭하면 img_onclick.jpg가 나타납니다. 그런 다음 img_onclick.jpg 이미지를 클릭하면 img.jpg가 다시 표시되기 전에 1000ms의 지연이 있어야합니다.
코드는 다음과 같습니다.
jQuery(document).ready(function($) {
$(".toggle-container").hide();
$(".trigger").toggle(function () {
$(this).addClass("active");
$(".trigger").find('img').prop('src', 'http://localhost:8888/images/img_onclick.jpg');
}, function () {
$(this).removeClass("active");
$(".trigger").find('img').prop('src', 'http://localhost:8888/images/img.jpg');
});
$(".trigger").click(function () {
$(this).next(".toggle-container").slideToggle();
});
});
사용 setTimeout()
:
var delayInMilliseconds = 1000; //1 second
setTimeout(function() {
//your code to be executed after 1 second
}, delayInMilliseconds);
없이 수행하려면 다음을 수행 setTimeout
하십시오 . 이 질문을 참조하십시오 .
setTimeout(function(){
}, 500);
내부에 코드를 배치하십시오 { }
500
= 0.5 초
2200
= 2.2 초
기타
자바 스크립트에는 두 가지 (주로 사용되는) 타이머 함수 유형이 setTimeout
있으며 setInterval
( other )
이 두 가지 방법 모두 동일한 서명이 있습니다. 콜백 기능과 지연 시간을 매개 변수로 사용합니다.
setTimeout
지연 후 한 번만 실행되는 반면 setInterval
모든 지연 밀리 초 후에는 콜백 함수를 계속 호출합니다.
이 두 가지 방법 모두 타이머가 만료되기 전에 지우는 데 사용할 수있는 정수 식별자를 반환합니다.
clearTimeout
그리고 clearInterval
이 두 방법은 상기 함수로부터 정수 리턴 식별자 걸릴 setTimeout
및setInterval
예:
alert("before setTimeout");
setTimeout(function(){
alert("I am setTimeout");
},1000); //delay is in milliseconds
alert("after setTimeout");
당신은 위의 코드를 실행하면 당신은 경고 것을 볼 수 before setTimeout
후 after setTimeout
마침내는 경고 I am setTimeout
1 초 (1000ms)으로 깜박임 후
예제에서 알 수있는 setTimeout(...)
것은 비동기입니다. 즉, 다음 명령문으로 가기 전에 타이머가 경과 할 때까지 기다리지 않습니다.alert("after setTimeout");
예:
alert("before setInterval"); //called first
var tid = setInterval(function(){
//called 5 times each time after one second
//before getting cleared by below timeout.
alert("I am setInterval");
},1000); //delay is in milliseconds
alert("after setInterval"); //called second
setTimeout(function(){
clearInterval(tid); //clear above interval after 5 seconds
},5000);
If you run the the above code you will see that it alerts before setInterval
and then after setInterval
finally it alerts I am setInterval
5 times after 1sec (1000ms) because the setTimeout clear the timer after 5 seconds or else every 1 second you will get alert I am setInterval
Infinitely.
How browser internally does that?
I will explain in brief.
To understand that you have to know about event queue in javascript. There is a event queue implemented in browser. Whenever an event get triggered in js, all of these events (like click etc.. ) are added to this queue. When your browser has nothing to execute it takes an event from queue and executes them one by one.
Now, when you call setTimeout
or setInterval
your callback get registered to an timer in browser and it gets added to the event queue after the given time expires and eventually javascript takes the event from the queue and executes it.
This happens so, because javascript engine are single threaded and they can execute only one thing at a time. So, they cannot execute other javascript and keep track of your timer. That is why these timers are registered with browser (browser are not single threaded) and it can keep track of timer and add an event in the queue after the timer expires.
same happens for setInterval
only in this case the event is added to the queue again and again after the specified interval until it gets cleared or browser page refreshed.
Note
The delay parameter you pass to these functions is the minimum delay time to execute the callback. This is because after the timer expires the browser adds the event to the queue to be executed by the javascript engine but the execution of the callback depends upon your events position in the queue and as the engine is single threaded it will execute all the events in the queue one by one.
Hence, your callback may sometime take more than the specified delay time to be called specially when your other code blocks the thread and not giving it time to process what's there in the queue.
And as I mentioned javascript is single thread. So, if you block the thread for long.
Like this code
while(true) { //infinite loop
}
Your user may get a message saying page not responding.
ES-6 Solution
Below is a sample code which uses aync/await to have an actual delay.
There are many constraints and this may not be useful, but just posting here for fun..
async function delay(delayInms) {
return new Promise(resolve => {
setTimeout(() => {
resolve(2);
}, delayInms);
});
}
async function sample() {
console.log('a');
console.log('waiting...')
let delayres = await delay(3000);
console.log('b');
}
sample();
If you need refresh, this is another posibility:
setTimeout(function () {
$("#jsSegurosProductos").jsGrid("refresh");
}, 1000);
Here is what I am doing to solve this issue. I agree this is because of the timing issue and needed a pause to execute the code.
var delayInMilliseconds = 1000;
setTimeout(function() {
//add your code here to execute
}, delayInMilliseconds);
This new code will pause it for 1 second and meanwhile run your code.
For sync calls you can use the method below:
function sleep(milliseconds) {
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > milliseconds){
break;
}
}
}
I'll give my input because it helps me understand what im doing.
To make an auto scrolling slide show that has a 3 second wait I did the following:
var isPlaying = true;
function autoPlay(playing){
var delayTime = 3000;
var timeIncrement = 3000;
if(playing){
for(var i=0; i<6; i++){//I have 6 images
setTimeout(nextImage, delayTime);
delayTime += timeIncrement;
}
isPlaying = false;
}else{
alert("auto play off");
}
}
autoPlay(isPlaying);
Remember that when executing setTimeout() like this; it will execute all time out functions as if they where executed at the same time assuming that in setTimeout(nextImage, delayTime);delay time is a static 3000 milliseconds.
What I did to account for this was add an extra 3000 milli/s after each for loop incrementation via delayTime += timeIncrement;
.
For those who care here is what my nextImage() looks like:
function nextImage(){
if(currentImg === 1){//change to img 2
for(var i=0; i<6; i++){
images[i].style.zIndex = "0";
}
images[1].style.zIndex = "1";
imgNumber.innerHTML = imageNumber_Text[1];
imgDescription.innerHTML = imgDescText[1];
currentImg = 2;
}
else if(currentImg === 2){//change to img 3
for(var i=0; i<6; i++){
images[i].style.zIndex = "0";
}
images[2].style.zIndex = "1";
imgNumber.innerHTML = imageNumber_Text[2];
imgDescription.innerHTML = imgDescText[2];
currentImg = 3;
}
else if(currentImg === 3){//change to img 4
for(var i=0; i<6; i++){
images[i].style.zIndex = "0";
}
images[3].style.zIndex = "1";
imgNumber.innerHTML = imageNumber_Text[3];
imgDescription.innerHTML = imgDescText[3];
currentImg = 4;
}
else if(currentImg === 4){//change to img 5
for(var i=0; i<6; i++){
images[i].style.zIndex = "0";
}
images[4].style.zIndex = "1";
imgNumber.innerHTML = imageNumber_Text[4];
imgDescription.innerHTML = imgDescText[4];
currentImg = 5;
}
else if(currentImg === 5){//change to img 6
for(var i=0; i<6; i++){
images[i].style.zIndex = "0";
}
images[5].style.zIndex = "1";
imgNumber.innerHTML = imageNumber_Text[5];
imgDescription.innerHTML = imgDescText[5];
currentImg = 6;
}
else if(currentImg === 6){//change to img 1
for(var i=0; i<6; i++){
images[i].style.zIndex = "0";
}
images[0].style.zIndex = "1";
imgNumber.innerHTML = imageNumber_Text[0];
imgDescription.innerHTML = imgDescText[0];
currentImg = 1;
}
}
참고URL : https://stackoverflow.com/questions/17883692/how-to-set-time-delay-in-javascript
'IT' 카테고리의 다른 글
C #에서 부울의 크기는 얼마입니까? (0) | 2020.06.24 |
---|---|
Eclipse 기본 설정으로 되돌리기 (0) | 2020.06.24 |
"종속성 분석"에 머물고있는 Cocoapods (0) | 2020.06.24 |
PowerShell에서 파일 버전 가져 오기 (0) | 2020.06.24 |
Java에서 Enum 켜기 (0) | 2020.06.24 |