2016-03-22 7 views
0

これは、最近のFlickrのアップロードからその検索語のいくつかの画像を検索してスクロールする基本的なウェブサイトのjavascriptコードです。cleartimeoutを使用して.getJSONの再帰的なsettimeout関数を停止するにはどうすればよいですか?

ボタンを押すとFlickr画像のスクロールが始まりますが、別の画像検索を入力してボタンをもう一度押すと、現在の画像のスクロールが停止し、新しい検索の画像がスクロールします期間。

問題は、元のスクロールが止まらず、すべてが2つに重なることです。

var main = function() { 
    var url = "http://api.flickr.com/services/feeds/photos_public.gne?tags="; 
    var end = "&format=json&jsoncallback=?"; 
    var input = document.querySelector("body input"); 
    var button = document.querySelector("body button"); 
    var images = document.querySelector("body .images"); 

    var buttonPressed = false; 

    //This is supposed to be the id of the current settimeout 
    var isTimeoutRunning; 

    button.addEventListener("click", function(event) { 
     if (!buttonPressed) { 
      buttonPressed = true; 
      console.log(buttonPressed); 
     } else { 
      //This should stop the timeout function before scrollImages 
      //gets called? 
      window.clearTimeout(isTimeoutRunning); 
      buttonPressed = false; 
      console.log(buttonPressed); 
     } 
     var value; 
     value = input.value; 
     $.getJSON((url + input.value + end), function(flickrResponse){ 
      scrollImages(0, flickrResponse); 
     }); 
    }); 
}; 

var scrollImages = function(cycle, obj) { 
    if (cycle === obj.items.length) { 
     console.log("end reached"); 
     cycle = 0; 
    } 
    var imgsrc = document.querySelector("body img"); 
    imgsrc.setAttribute("src", obj.items[cycle].media.m); 

    isTimeoutRunning = setTimeout(function() { 
     console.log(isTimeoutRunning); 
     cycle += 1; 
     scrollImages(cycle, obj); 
    }, 2000) 
}; 

答えて

1

あなたは、あなたの二つの機能外isTimeoutRunningを定義する必要があります例えば

var isTimeoutRunning; 

var main = function() { 
    // don't redefine isTimeoutRunning here 

    // ... etc 
} 
var scrollImages = function(cycle, obj) { ... } 

問題がscrollImagesisTimeoutRunning、すなわちwindow.isTimeoutRunning、グローバルとして定義されていることです。これは、mainで定義された変数とは異なる変数です。

+0

これが解決しました。ありがとう! – HsinWang5

関連する問題