setInterval不会退出循环

时间:2013-01-29 06:56:21

标签: javascript jquery

以下javascript代码从数组中随机选择值并在输入框中键入它。我用过jquery。我想结束setInterval“zaman2”,所以在它结束后我可以重新输入下一个随机字符串到输入框。但循环不会结束并卡住。我怎么解决这个问题? 链接到jsFiddle:http://jsfiddle.net/AQbq4/4/

var dersler = [...very long list...];
var zaman = setTimeout(function() {
    var yeniDers = dersler[Math.floor(Math.random()*dersler.length)];
    sayac = 0;
    var zaman2 = setInterval(function() {
            var harf = yeniDers.slice(0,(sayac+1));
            sayac++;
            $('#main-search').attr('placeholder', harf).typeahead({source: dersler});
        if (sayac == yeniDers.length) {
            clearInterval(zaman2);
        }
    },450);
},2000);

1 个答案:

答案 0 :(得分:0)

你不是说

DEMO

var tId, tId2;
function show() {
    var ran = arr[Math.floor(Math.random()*arr.length)];
    cnt = 0;
    tId = setInterval(function() {
            var char = ran.slice(0,(cnt+1));
            cnt++;
            $( '#main-search' ).attr('placeholder', char);
        if (cnt == ran.length) {
            clearInterval(tId);
            tId2=setTimeout(show,2000);
        }
    },450);
}
show();