2016-12-25 45 views
-1

任何人都可以幫我clearInterval?我一直在使用它幾個小時,似乎無法讓它工作。我使用的是非常相似的代碼,我在W3學校發現如下:Javascript - clearInterval

這裏也是一個鏈接在行動上看到:http://hyque.com/ani/drawImageBtn.html

<!doctype html> 
<html> 
<head> 
<meta charset="utf-8"> 
<title>DrawImage with Buttons</title> 
</head> 

<body> 

<button id="startBtn">Start</button> 
<button id="stopBtn">Stop</button><br /> 

<canvas id="myCanvas" width="125" height="187" style="border:1px solid  #d3d3d3;"> 

<script> 


window.onload = function() { 
var c = document.getElementById("myCanvas"); 
var ctx = c.getContext("2d"); 
var img = new Image(); 
img.src = "http://hyque.com/ani/adam.png"; 
var xPos = 0; 

ctx.drawImage(img, 0, 0, 120, 182, 0, 0, 120, 182); 

var el = document.getElementById('startBtn'); 
el.addEventListener('click', strt, false); 

var el2 = document.getElementById('stopBtn'); 
el2.addEventListener('click', stopIt, false); 

function imageXPosition() { 


ctx.clearRect(0, 0, 120, 182); // This clears the canvas 

ctx.drawImage(img, xPos, 0, 120, 182, 0, 0, 120, 182); //Draws the individual frames 


xPos += 120; //adds the width 

//This adds 1 to the second frame 
if(xPos == 120){ 
    xPos += 1; 
} 
if(xPos > 841){xPos = 0;} // This resets to 0 after the las frame 


} 
function strt(){ 
var intStp = setInterval(imageXPosition, 200); 

} 
function stopIt(){ 
    clearInterval(intStp); 
} 
} 

</script> 
</body> 
</html> 
+0

'var intStp'只在'strt()'內是本地作用域。您無法在該功能之外訪問它 – charlietfl

回答

2

你可以看看作用域:

var intStp; 
function strt(){ 
intStp = setInterval(imageXPosition, 200); 
} 
function stopIt(){ 
clearInterval(intStp); 
} 

只有當函數結束時,函數內部的變量纔會存在,除非它不會綁定到內部函數(請參閱Closure)。

function(){ 
var a;//a is declared 
} 
//a is deleted 

函數不能訪問其他函數屬性,除非它正在訪問外部函數的變量。

您可以閱讀MDN:JS的作用域,函數,變量(主要是:基礎知識)在局部範圍內啓動功能

+0

工作正常。非常感謝。我想知道這是否是範圍問題。我想這是學習過程的一部分。 –

+0

關於學習進度:請將其標記爲答案;)(告訴其他幫手,你已經滿意...) –

-1

IntStp變量。只需省略var關鍵字

+0

不是一個優雅的方式,順便說一句... –

+0

這是一個不好的做法。應該總是在適當的範圍內聲明變量 – charlietfl

相關問題