2012-08-06 30 views
0

我想在两者之间重置此闪光灯,这样我不必等到结束才能重新启动闪光灯,我该如何重置?需要重置功能我该怎么做

function flash() { 
var arrayId = 0, 
    splitSet = $('#text_original').html().split(" "), 
    splitSetLength = splitSet.length; 


function flashWord() { 
    $("#flash_word").html(splitSet[arrayId]); 
    arrayId += 1; 
    var t = setTimeout(remove, 1000); 
} 

function remove() { 
    if (arrayId < splitSetLength) { 
     $("#flash_word").html(" "); 
     flashWord(); 
    } //else reset_flash(); 
} 
flashWord(); } 

请参阅http://jsfiddle.net/HcDfS/

回答

1

使定时器变量一个全球性并取消超时就可以了(与clearTimeout())。然后,隐藏#flash_word

我把重新实现你的提琴的自由:

var timer, words; 

function startFlashing() { 
    words = $("#source").text().split(" "); 
    showNextWord(0); 
} 

function stopFlashing() { 
    clearTimeout(timer); 
    $("#banner").text(""); 
} 

function showNextWord(index) { 
    $("#banner").text(words[index]); 
    index++; 
    if (index < words.length) timer = setTimeout(function() { 
     showNextWord(index); 
    }, 1000); 
    else $("#banner").text(""); 
} 

随着HTML:

<p id="source">This is the text to be flashed.</p> 
<button onclick='startFlashing()'>Start Flashing!</button> 
<button onclick='stopFlashing()'>Stop Flashing!</button> 
<p id="banner"></p>​ 

而且它在这里:http://jsfiddle.net/CZnVc/6/

+0

,但闪光灯暂时停止响应,并再次重新启动点击停止 – 2012-08-06 18:48:59

+0

@srijibmandal对不起,我忘了分配'定时器'变量与'setTimeout'结果 - 我基本上没有一个dd'timer ='在代码中'setTimeout'前面。我更新了它,现在它工作。 – 2012-08-06 18:53:31

+0

我曾尝试将时间变量赋值给setTimeout,但是我错误地这样做了:var timer = setTimeout(function(){ showNextWord(index); },1000);'我把'var'这个词折腾..谢谢@Randy – 2012-08-07 07:28:15