www.webdeveloper.com
Page 1 of 2 12 LastLast
Results 1 to 15 of 27

Thread: pausing/resuming setinterval() and not reset it

  1. #1
    Join Date
    Aug 2014
    Posts
    13

    pausing/resuming setinterval() and not reset it

    Actually i am not that great with JS but i try to learn and i tried solving my own issue for 2 days but i couldn't fix it so i am here to ask for help. my problem is i am trying to pause and resume count down timer with setinterval(); and when i use clearinterval(); it reset it when i recall setinterval(); again. here is my code:
    Code:
    <script type='text/javascript'>
    document.getElementById('myVideo').addEventListener('playing',myHandler,false);
        function myHandler(e) {
            if(!e) { e = window.event; }
    
        $("#box").hide();  
    
    
    var replay = document.getElementById("replay");  
    var container = document.getElementById('dl');
    var seconds = 10;
    var timer;
    var isPaused = false;
    
    
    
    function countdown() {
    seconds--;
    
        if(seconds > 0 && !myVideo.paused) {
    isPaused = false;
    
    if(!isPaused) {
    
            container.innerHTML = '<font color="black"> You can Skip the Ad after <b>'+seconds+'</b> seconds.. </font>';
    
       }
        } else if (seconds > 0 && myVideo.paused)
    {
         isPaused = true;
    clearInterval(timer);
        }else {
           
      $("#dl").hide();
    $("#MyButton").css({
    'cursor':'pointer',
    'display':'block'})  
      $("#replay").css({
    'cursor':'pointer',
    'display':'block',
    'background-color':'#ffffff',
      'color':'#3399ff',
    'border':'2px solid #ffffff',
    'border-radius' : '25px'
    })
    clearInterval(timer);
        }
    }
     timer = window.setInterval(countdown, 1000);
        }
     
    </script>

    it works when i pause it but when i play vid again the timer count down from the start (10) and when i remove the clearinterval(); that inside

    Code:
    else if (seconds > 0 && myVideo.paused)
    {
         isPaused = true;
    clearInterval(timer);
        }
    this conditional, it actually kinda work by continue previous count down but bring with it new count down so it like go back and forth between paused second and new one.


    what i need to accomplish from this code briefly:

    1- when video first time plays which is when the page loads for first time the count down timer begins from (0secs)

    2- if user paused the video the count down pause as well with the video.

    3- when user play again the video after the pause the count down timer continue counting from second the user did paused at and not from begining.

    4- restart back by counting down new 10 seconds when clicking replay button (this replay button don't show up except when 10 seconds end tho).

    point 1,2 and 4 already work in the code i provided above but my all problem is number 3 which is when i play the video again after a pause the count down begins counting from 10 if i include a clearInterval(); in condition of video.paused(); or if i didnt include clearInterval(); it will continue counting down from second i paused from but begining new one from 10 and timer keeps swinging between continued second and new one... if i only can stop new timer from begining it will be great and thats all i want and missing for me.

    thats all and hopefully i get help from someone soon

    Yours,
    Maxwel

  2. #2
    When you clear it, it stops existing -- you never set it again... when you unpause, you have to do a:

    timer = window.setInterval(countdown, 1000);

    Again.

    It's hard to say much more about your problem without seeing the markup being manipulated, but it might help if you didn't set CSS from the markup, had code formatting that made the least bit of sense, weren't using innerHTML to put tags like FONT into the page that have no business on any site written after 1997, and it also might not be a bad idea. You also don't have to say "VAR" multiple times if making multiple VAR in a row, you can comma delimit them instead.

    I'd also NOT do a decrement on your seconds until I knew the state of the value... and I'd probably axe the jQuery that's not doing a blasted thing for you other than encouraging bad coding habits.

    Again though, I'd have to see more of the big picture to provide real help -- I also have the feeling you omitted some scripting as there's a lot of handler stuff on which this should be reliant that I'm not seeing.

    But again, that's why snippets suck. It's like doing brain surgery through a keyhole without an endoscope.

  3. #3
    Join Date
    Aug 2014
    Posts
    13
    hey deathshadow,
    At first, i want to thank you cuzi really learnt much from ur above post and will clean up my code by following what u mentioned above and i am glad that there are ppl out there love to help like you. (gonna book mark this thread cuz of ur above post for later too)

    Secondly, do u mind pming the code instead? cuz i wont be able to post it all here


    Thanks again,

    Maxwel

  4. #4
    No problem if you want to PM it, but you may have to link, the PM system here is limited to 2k messages.

    With a rather tiny maximum box size as I've also discovered to my dismay

  5. #5
    Join Date
    Mar 2007
    Location
    localhost
    Posts
    2,498
    IMHO either use a JQuery or similar framework and ask in the JavaScript frameworks forum for help or just use JavaScript itself.

    When using time elements you should use time itself and not attempt to track time with a variable, any number of bottlenecks in a system can cause overheads that then cause a script to lag, even with the best system, you will find that your browser has some lag because of hooking elements and creating events all take time which can mean a small difference in what you start with on countdown

    Example...

    Code:
    <div id="time"></div>
    <script>
    target = document.getElementById("time");
    endTime = new Date().getTime() +  30000; // 30 sec's in ms
    
    function update(){
     t=new Date().getTime(); // time reference NOW!
     s = Math.floor( (endTime - t) / 1000); // how much time left
     if( t > endTime ) clearInterval(x);
     else target.innerHTML = s + " Sec.";
    }
    
    x = setInterval("update()",1000);
    </script>
    Yes, I know I'm about as subtle as being hit by a bus..(\\.\ Aug08)
    Yep... I say it like I see it, even if it is like a baseball bat in the nutz... (\\.\ Aug08)
    I want to leave this world the same way I came into it, Screaming, Incontinent & No memory!
    I laughed that hard I burst my colostomy bag... (\\.\ May03)
    Life for some is like a car accident... Mine is like a motorway pile up...

    Problems with Vista? :: Getting Cryptic wid it. :: The 'C' word! :: Whois?

  6. #6
    ~\\.\ so your answer to overhead and memory issues is to throw more code at it? Especially the slow and overhead-wasting time function and complex math? AND the ridiculous bloated overhead of the fat bloated idiotic "framework" while at it?!?

    That makes sense.

    ... also doesn't address starting and stopping based on the video's status, which is the OP's question... which using your method the handler for starting/stopping would have to recreate endTime in addition to calling setInterval again.

    Well, unless one were to just allow setInterval to run and not do anything while the video is paused... As much of a "waste" of processing time as it might be, it might be the smoother way of handling it.

  7. #7
    Join Date
    Aug 2014
    Posts
    13
    Idk how to pm u! I can't find any PM button on your profile! Any idea?

    Sorry for late reply but had rl tasks here

    Thanks alot for accepting me to pm you and for all the help,
    Maxwel

  8. #8
    Join Date
    Mar 2007
    Location
    localhost
    Posts
    2,498
    Quote Originally Posted by deathshadow View Post
    ~\\.\ so your answer to overhead and memory issues is to throw more code at it? Especially the slow and overhead-wasting time function and complex math? AND the ridiculous bloated overhead of the fat bloated idiotic "framework" while at it?!?

    That makes sense.

    ... also doesn't address starting and stopping based on the video's status, which is the OP's question... which using your method the handler for starting/stopping would have to recreate endTime in addition to calling setInterval again.

    Well, unless one were to just allow setInterval to run and not do anything while the video is paused... As much of a "waste" of processing time as it might be, it might be the smoother way of handling it.
    setInterval is only set once as is the endtime, for the OP and their query about pausing, theirs no point in pausing a countdown that is limiting the playback of a video if the person has to wait 30 seconds.

    I am making a big assumption here that what the OP really wants is a bypass of some sort for people who have either subscribed or paid for immediate access.

    Each time the function is called, the only recalculation is the time remaining and if it has expired, the interval timer is canceled.

    With a bit of modification, the code could initiate play() feature of the video that is being timed out.

    As for the scathing comment from yourself, what are you proposing? all you have done so far is criticize the OP and my offering of a possible resolution to the problem.

    Perhaps you should stop criticizing other people and if you feel that you can contribute, post, otherwise keep your thoughts to yourself and butt out because the more you keep this up, the more of a tool you are becoming.
    Yes, I know I'm about as subtle as being hit by a bus..(\\.\ Aug08)
    Yep... I say it like I see it, even if it is like a baseball bat in the nutz... (\\.\ Aug08)
    I want to leave this world the same way I came into it, Screaming, Incontinent & No memory!
    I laughed that hard I burst my colostomy bag... (\\.\ May03)
    Life for some is like a car accident... Mine is like a motorway pile up...

    Problems with Vista? :: Getting Cryptic wid it. :: The 'C' word! :: Whois?

  9. #9
    Join Date
    Aug 2014
    Posts
    13
    guys i am simply trying to do something like youtube ads system. so i want when the user pause the vid the countdown timer pause as well and when he press play again it continue the count down from where he paused not from the begining thats simply what i am trying to do with this JS code

  10. #10
    Join Date
    Mar 2007
    Location
    localhost
    Posts
    2,498
    If you use HTML5 and the <video> tag, you can gather stream information like time position and also seek to times, perhaps if you were more clear about your intentions then your answer would have come quicker. TBH I have never seen ads on youtube, so I don't know how they operate.
    Yes, I know I'm about as subtle as being hit by a bus..(\\.\ Aug08)
    Yep... I say it like I see it, even if it is like a baseball bat in the nutz... (\\.\ Aug08)
    I want to leave this world the same way I came into it, Screaming, Incontinent & No memory!
    I laughed that hard I burst my colostomy bag... (\\.\ May03)
    Life for some is like a car accident... Mine is like a motorway pile up...

    Problems with Vista? :: Getting Cryptic wid it. :: The 'C' word! :: Whois?

  11. #11
    Join Date
    Aug 2014
    Posts
    13
    @\\.\ Thanks alot but thats not what i want still what i want is to be able to pause and continue countdown timer from where i paused it. its not anything related to video or its playback. this count down timer is completely seperate from video and its position.

    Thanks alot again for all the help,

    Maxwel

  12. #12
    I'm getting what you're asking, that's why I suggested simply letting the timer update run, but not update while video.paused is true.

    Something like:

    Code:
    function countdown() {
    	if (myVideo.paused) return;
    	if (!myVideo.ended) {
    		if (seconds--) {
    			container.innerHTML = 'You can skip the ad after ' + seconds + ' seconds.';
    			return;
    		}
    		container.innerHTML = 'Put your skip link here';
    	}
    	clearInterval(timer);
    }
    Using return to short-circuit our way out reduces the total code and the overhead slightly. You pause the video element, just let the timer run rather than play with it -- one interval every second isn't going to break the bank. Seconds hits 0, show the advert. Remember, 0 is the same as false during a loose compare, so you can decrement and check all-in-one.

    That's really all you're trying to do there, right? Count down showing how long before they can skip what I assume is an advert, then replace the skip text with the link to skip, halting the countdown if the advert ends, the timer ends, and not doing anything if the video is paused.

    Leaving it running means you don't have to hook your video's play button to resume the counter.

  13. #13
    Quote Originally Posted by \\.\ View Post
    I am making a big assumption here that what the OP really wants is a bypass of some sort for people who have either subscribed or paid for immediate access.
    That's NOT what's being asked. So you've basically never used youtube? I understood the question, I just need to see a HELL of a lot more of the OP's code to even try and offer a realistic solution and ways to fix what is -- to be frank -- a hell of a lot of bad code.

    Quote Originally Posted by \\.\ View Post
    As for the scathing comment from yourself, what are you proposing? all you have done so far is criticize the OP and my offering of a possible resolution to the problem.
    I asked for clarification AND said a possible solution, which I just elaborated on.

    As to your "offering" it has not one thing to do with what they were asking -- hence the NEED for clarification.
    Last edited by deathshadow; 08-10-2014 at 03:27 AM.

  14. #14
    Join Date
    Aug 2014
    Posts
    13
    hey Deathshadow,

    Thanks for all the help and support and yes u got me this time right and i changed my code to look like that:

    Code:
    var replay = document.getElementById("replay");  
    var container = document.getElementById('dl');
    var seconds = 10;
    var timer;
    var isPaused = false;
    
    
    function countdown() {
    
        if (myVideo.paused){ return;
    }
    if (!myVideo.ended) {
    		if (seconds--) {
      
    
            container.innerHTML = '<font color="black"> You can Skip the Ad after <b>'+seconds+'</b> seconds.. </font>';
    return;
    		}
        
           
      $("#dl").hide();
    $("#MyButton").css({
    'cursor':'pointer',
    'display':'block'})  
      $("#replay").css({
    'cursor':'pointer',
    'display':'block',
    'background-color':'#ffffff',
      'color':'#3399ff',
    'border':'2px solid #ffffff',
    'border-radius' : '25px'
    })
        }
    	clearInterval(timer);
    }
     timer = window.setInterval(countdown, 1000);
        }
    my play pause js script is as simple as myVid.play(); and myVid.pause();

    but the problem is that when i pause the video then replay it the counter begin new count down and keep going back and forth between old and new one which was same issue i had with me other code. any suggestions?

  15. #15
    I'd have to see more of that code, but it looks like you're setting it again after the clear... which you do NOT want to do.

    Side note, you don't need to say VAR so much as you can comma delimit them, if you're only doing a return don't waste time with extra {} around it.... some indentation that makes sense would help, and I REALLY suggest axing that jQuery nonsense and playing games with the CSS from the scripting. That's NOT good coding practices. (gee, jQuery promoting sleazy / bad practices, who knew?). This is also 2014 not 1998, STOP USING THE BLASTED FONT TAG. Likewise time is not a proper name or book title, why are you putting <b> around it?

    You're also missing some semi-colons.

    AHA, in formatting it, you've got the clearInterval AFTER the function instead of inside it. It needs to be swapped with the } before it. Goes next to that jQuery-tardery, not after the }

    Here it is formatted and cleaned up, with that swap made.

    Code:
    		var
    			replay = document.getElementById("replay"),
    			container = document.getElementById('dl'),
    			seconds = 10,
    			timer;
    
    		function countdown() {
    			if (myVideo.paused) return;
    			if ((!myVideo.ended) && (seconds--)) {
    				container.innerHTML = 'You can Skip the Ad after <span>'+seconds+'</span> seconds...';
    				return;
    			}
    			$("#dl").hide();
    			$("#MyButton").css({
    				'cursor':'pointer',
    				'display':'block'
    			});
    			$("#replay").css({
    				'cursor':'pointer',
    				'display':'block',
    				'background-color':'#ffffff',
    				'color':'#3399ff',
    				'border':'2px solid #ffffff',
    				'border-radius' : '25px'
    			});
    			clearInterval(timer);
    		}
    	}
    	timer = window.setInterval(countdown, 1000);
    }
    If you don't clear it when it ends, it will keep trying to run over and over... Though I'm not sure why the count would start over unless this is in some function you are calling unnecessarily on resume. Given the number of closing { I'm assuming that's the case, which is why I need to see ALL of it, not just a snippet to advise further.

    Though really I'd have THREE outcomes, not two. the countdown, the skip link, video ended.
    Last edited by deathshadow; 08-11-2014 at 02:23 AM.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles