I have come up with the following code, which allows users to view a page with a movie embed for 30 seconds before redirecting them away from the page. Additionally, they can click a link to hide the div with this countdown. What I need help with is canceling the redirect (stopping it from happening) if that link is clicked, so users can continue to watch the full movie. Thanks in advance for your help!
Javascript:
<script type="text/javascript">
var settimmer = 0;
$(function(){
window.setInterval(function() {
var timeCounter = $("b[id=show-time]").html();
var updateTime = eval(timeCounter)- eval(1);
$("b[id=show-time]").html(updateTime);
if(updateTime == 0){
window.location = ("redirect.php");
}
}, 1000);
});
</script>
<script type="text/ja开发者_StackOverflow社区vascript">
$(document).ready(function(){
$(".slidingDiv").show();
$(".show_hide").show();
$('.show_hide').click(function(){
$(".slidingDiv").slideToggle();
});
});
</script>
HTML:
<div id="my-timer" class="slidingDiv">
You have <b id="show-time">30</b> seconds to decide on this movie.
<a href="#" class="show_hide">Yes, I want to watch this one!</a>
</div>
setInterval
returns a value you can use to cancel the interval timer via clearInterval
. So:
$(function(){
// +--- Remember the value from `setInterval
// |
// v
var timerHandle = window.setInterval(function() {
var timeCounter = $("b[id=show-time]").html();
var updateTime = eval(timeCounter)- eval(1);
$("b[id=show-time]").html(updateTime);
if(updateTime == 0){
window.location = ("redirect.php");
}
}, 1000);
// + Hook up a handler for the link that uses the handle to clear it
// |
// v
$("selector_for_the_link").click(function() {
clearInterval(timerHandle);
timerHandle = 0;
});
});
Note that I've put the variable inside your ready
function, so it isn't a global.
Off-topic: You don't need or want to use eval
in the above (in fact, you virtually never want to use eval
at all, for anything). If you want to parse a string to make a number, use parseInt
(and there's never any reason to eval a literal like 1
). So this line:
var updateTime = eval(timeCounter)- eval(1);
becomes
var updateTime = parseInt(timeCounter, 10) - 1;
(The 10
means the string is in decimal — e.g., base 10.)
You need to use the clearInterval method.
Maybe you can use setTimeout() to do so rather than setInterval().Here is a sample.
精彩评论