这是一个基本网站的 javascript 代码,该网站采用搜索词并滚动浏览最近 Flickr 上传的该搜索词的一些图像。
当用户按下按钮时,它将开始滚动浏览 Flickr 图像,但是如果他输入另一个图像搜索并再次按下按钮,当前图像滚动应该停止,并且应该滚动浏览新搜索词中的图像。
问题是原来的滚动并没有停止,它所做的只是使两者重叠。
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)
};
最佳答案
您需要在两个函数之外定义isTimeoutRunning
,例如
var isTimeoutRunning;
var main = function() {
// don't redefine isTimeoutRunning here
// ... etc
}
var scrollImages = function(cycle, obj) { ... }
问题在于,scrollImages
中的isTimeoutRunning
被定义为全局的,即window.isTimeoutRunning
。这是与 main
中定义的变量不同的变量。
关于javascript - 如何使用cleartimeout来停止.getJSON中的递归settimeout函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36146014/