我正在创建一个用户操作的随机选择器。用户点击一个按钮,系统会选择两个随机结果(这将是视频)。立即停止setTimeout循环而不结束当前循环
页面会交替突出显示两个随机结果 - 用户可以再次点击该按钮,并可以选择他们想要的视频。
它的所有工作都很好,但交替突出显示是用setTimeout循环完成的,而不是立即停止。
我该如何得到它,以便当用户按下'select'按钮时,flit函数会立即停止 - 而不是当前循环结束?
这里的小提琴
http://jsfiddle.net/zandergrin/tmwst5z9/4/
PS - 抱歉,但这是progrees工作 - 我知道有一个在这里的几个凌乱位... VAR间隔= 0;
function random() {
// create the array
var posts = ["post 1", "post 2", "post 3", "post 4", "post 5", "post 6", "post 7", "post 8", "post 9", "post 10"];
var results = posts
// Shuffle array
.sort(function() {
return .5 - Math.random()
})
// Get first 2 items
.slice(0, 2);
var post1 = results[0];
var post2 = results[1];
// add them to the DOM
$('#res1').html(post1);
$('#res2').html(post2);
// loop it
interval = setTimeout(random, 100);
}
function start() {
// Hide the start button
$("#start").css("display", "none");
$("#stop").css("display", "block");
// Start the randomizer
random();
}
function stop() {
// Hide the stop button and stop the random() timeout
clearTimeout(interval);
$("#stop").css("display", "none");
$("#select").css("display", "block");
// set the inital background colour
$("#res1").css({'background': '#123','color': '#fff'});
$("#res2").css({'background': '#eee','color': '#000'});
//create a function to flick between items
function flit() {
//color the results
setTimeout(function() {
$("#res1").css({'background': '#eee','color': '#000'});
$("#res2").css({'background': '#123','color': '#fff'});
}, 800);
//colour again after a delay
setTimeout(function() {
$("#res1").css({'background': '#123','color': '#fff'});
$("#res2").css({'background': '#eee','color': '#000'});
}, 1600);
//loop it
timer = setTimeout(arguments.callee, 1600);
};
//run the flick function
flit();
}
function select() {
// stop thie flit function - doesnt stop immediately!
clearTimeout(timer);
$("#select").css("display","none");
$("#refresh").css("display", "block");
}
function refresh() {
location.reload();
}
只是一个提示:排序由'0.5 - 的Math.random()'并不是洗牌数组的最佳方法,因为它允许'a> b && b> c && c> a'为真,这可能会严重混淆'sort'实现。一个简单的shuffle是'.map(function(x){return [Math.Random(),x];})。sort(function(a,b){return a [0] -b [0];})。 map(function(x){return x [1];})'。为了提高效率,谷歌Knuth Fisher-Yates洗牌。 – 2014-11-04 19:19:52
非常感谢 - 我曾阅读Knuth Fisher-Yates shuffle。我理解了这个推理,但是如果我诚实的话,我的搜索引擎的大部分实现都会超出我的头脑。现在就使用它... – JorgeLuisBorges 2014-11-05 09:10:39
要明确一点,该代码不是Knuth-Fisher-Yates,它只是一个安全,不偏不倚的洗牌,但效率不如KFY。 – 2014-11-05 19:18:12