H5 타이머 requestAnimationFrame 사용 팁
이번에는 H5의 timerrequestAnimationFrame 사용 팁을 알려드리겠습니다. H5 타이머 requestAnimationFrame 사용 시 주의사항은 무엇인가요?
requestAnimationFrame이 등장하기 전에는 일반적으로 setTimeout과 setInterval을 사용했는데, html5에서 새로운 requestAnimationFrame을 추가한 이유는 무엇일까요?
장점 및 특징:
1) requestAnimationFrame은 각 프레임의 모든 DOM 작업에 집중하여 한 번의 다시 그리기 또는 리플로우로 완료하며, 다시 그리기 또는 리플로우 시간 간격이 빡빡합니다. 브라우저의 새로 고침 빈도를 따릅니다.
2) 숨겨진 요소나 보이지 않는 요소에서는 requestAnimationFrame이 다시 그리거나 리플로우되지 않습니다. 이는 물론 CPU, GPU 및 메모리 사용량이 적음을 의미합니다.
3) requestAnimationFrame은 애니메이션을 위해 특별히 브라우저에서 제공하는 API입니다. 브라우저는 자동으로 메소드 호출을 최적화합니다. 런타임 중에 페이지가 활성화되지 않으면 애니메이션이 자동으로 일시 중지되어 CPU 오버헤드를 효과적으로 절약합니다. 한마디로 말하면 이 제품의 성능은 높고 화면이 멈추지 않으며 프레임 속도가 다른 브라우저에 따라 자동으로 조정됩니다. 이해하지 못하더라도 상관없습니다. 이는 브라우저 렌더링 원리와 관련이 있습니다. 먼저 사용법을 배워봅시다!
requestAnimationFrame을 사용하는 방법은 무엇입니까?
사용법은 타이머 setTimeout과 유사합니다. 차이점은 시간 간격 매개변수를 설정할 필요가 없다는 점입니다.
var timer = requestAnimationFrame( function(){ console.log( '定时器代码' ); } );
매개변수는
콜백 함수이며 반환 값은 타이머 번호를 나타내는 데 사용되는 정수입니다. <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script>
window.onload = function(){
var aInput = document.querySelectorAll( "input" ),
timer = null;
aInput[0].onclick = function(){
timer = requestAnimationFrame( function say(){
console.log( 1 );
timer = requestAnimationFrame( say );
} );
};
aInput[1].onclick = function(){
cancelAnimationFrame( timer );
}
}
</script>
</head>
<body>
<input type="button" value="开启">
<input type="button" value="关闭">
</body>
</html>
이 메서드는 호환되어야 합니다.
간단한 호환성:
window.requestAnimFrame = (function(){ return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || function( callback ){ window.setTimeout(callback, 1000 / 60); }; })();
브라우저가 AnimationFrame을 인식하지 못하는 경우 호환성을 위해 setTimeout을 사용하세요.
3가지 다른 타이머 사용(setTimeout, setInterval) , requestAnimationFrame)은 진행률 표시줄 로드를 구현합니다.
1. setInterval 메서드:<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
p{
width:0px;
height:40px;
border-radius:20px;
background:#09f;
text-align:center;
font:bold 30px/40px '微软雅黑';
color:white;
}
</style>
<script>
window.onload = function(){
var oBtn = document.querySelector( "input" ),
oBox = document.querySelector( "p" ),
timer = null, curWidth = 0,
getStyle = function( obj, name, value ){
if( obj.currentStyle ) {
return obj.currentStyle[name];
}else {
return getComputedStyle( obj, false )[name];
}
};
oBtn.onclick = function(){
clearInterval( timer );
oBox.style.width = '0';
timer = setInterval( function(){
curWidth = parseInt( getStyle( oBox, 'width' ) );
if ( curWidth < 1000 ) {
oBox.style.width = oBox.offsetWidth + 10 + 'px';
oBox.innerHTML = parseInt( getStyle( oBox, 'width' ) ) / 10 + '%';
}else {
clearInterval( timer );
}
}, 1000 / 60 );
}
}
</script>
</head>
<body>
<p>0%</p>
<p><input type="button" value="ready!Go"></p>
</body>
</html>
<script>
window.onload = function(){
var oBtn = document.querySelector( "input" ),
oBox = document.querySelector( "p" ),
timer = null, curWidth = 0,
getStyle = function( obj, name, value ){
if( obj.currentStyle ) {
return obj.currentStyle[name];
}else {
return getComputedStyle( obj, false )[name];
}
};
oBtn.onclick = function(){
clearTimeout( timer );
oBox.style.width = '0';
timer = setTimeout( function go(){
curWidth = parseInt( getStyle( oBox, 'width' ) );
if ( curWidth < 1000 ) {
oBox.style.width = oBox.offsetWidth + 10 + 'px';
oBox.innerHTML = parseInt( getStyle( oBox, 'width' ) ) / 10 + '%';
timer = setTimeout( go, 1000 / 60 );
}else {
clearInterval( timer );
}
}, 1000 / 60 );
}
}
</script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
p{
width:0px;
height:40px;
border-radius:20px;
background:#09f;
text-align:center;
font:bold 30px/40px '微软雅黑';
color:white;
}
</style>
<script>
window.onload = function(){
var oBtn = document.querySelector( "input" ),
oBox = document.querySelector( "p" ),
timer = null, curWidth = 0,
getStyle = function( obj, name, value ){
if( obj.currentStyle ) {
return obj.currentStyle[name];
}else {
return getComputedStyle( obj, false )[name];
}
};
oBtn.onclick = function(){
cancelAnimationFrame( timer );
oBox.style.width = '0';
timer = requestAnimationFrame( function go(){
curWidth = parseInt( getStyle( oBox, 'width' ) );
if ( curWidth < 1000 ) {
oBox.style.width = oBox.offsetWidth + 10 + 'px';
oBox.innerHTML = parseInt( getStyle( oBox, 'width' ) ) / 10 + '%';
timer = requestAnimationFrame( go );
}else {
cancelAnimationFrame( timer );
}
} );
}
}
</script>
</head>
<body>
<p>0%</p>
<p><input type="button" value="ready!Go"></p>
</body>
</html>
추천 자료:
H5의 드래그 앤 드롭에 대한 자세한 설명캔버스를 사용하여 동영상에서 공세 효과 얻기위 내용은 H5 타이머 requestAnimationFrame 사용 팁의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제











HTML의 테이블 테두리 안내. 여기에서는 HTML의 테이블 테두리 예제를 사용하여 테이블 테두리를 정의하는 여러 가지 방법을 논의합니다.

HTML의 Nested Table에 대한 안내입니다. 여기에서는 각 예와 함께 테이블 내에 테이블을 만드는 방법을 설명합니다.

HTML 여백-왼쪽 안내. 여기에서는 HTML margin-left에 대한 간략한 개요와 코드 구현과 함께 예제를 논의합니다.

HTML 테이블 레이아웃 안내. 여기에서는 HTML 테이블 레이아웃의 값에 대해 예제 및 출력 n 세부 사항과 함께 논의합니다.

HTML 입력 자리 표시자 안내. 여기서는 코드 및 출력과 함께 HTML 입력 자리 표시자의 예를 논의합니다.

HTML 순서 목록에 대한 안내입니다. 여기서는 HTML Ordered 목록 및 유형에 대한 소개와 각각의 예에 대해서도 설명합니다.

HTML에서 텍스트 이동 안내. 여기서는 Marquee 태그가 구문과 함께 작동하는 방식과 구현할 예제에 대해 소개합니다.

HTML onclick 버튼에 대한 안내입니다. 여기에서는 각각의 소개, 작업, 예제 및 다양한 이벤트의 onclick 이벤트에 대해 설명합니다.
