www.webdeveloper.com
Page 2 of 2 FirstFirst 12
Results 16 to 27 of 27

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

  1. #16
    Join Date
    Aug 2014
    Posts
    13
    hey deathshadow,

    i really appreciate all the help and support u offer and i am sorry for bothering much but here is the whole JS concerning the count down timer. if u want me to provide whole php script i will do but i donno how to pm u through forums here. i can't see any pm button to be able to do that.

    i tried ur script but it still go back and forth between old and new one when i stop then resume the video like it used to do before. maybe cuz adding the playing eventlistener? idk. i was about to clean my whole code according to ur first post but after i get this working first.

    Code:
    <script type='text/javascript'>
    
    document.getElementById('myVideo').addEventListener('playing',myHandler,false);
    
        function myHandler(e) {
            if(!e) { e = window.event; }
    
        $("#box").hide();  
     $("#pause").show(); 
    $("#clickhere").hide(); 
    
    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);
    	}
    
     
    </script>
    Play/pause code:

    Code:
    <script type='text/javascript'>
    
    
    function play() {
    if (myVideo.paused){ 
             myVideo.play();
    $("#play").hide();
    $("#pause").show();
    
    }}
    
    function pause() {
    if (!myVideo.paused){ 
             myVideo.pause(); 
    $("#pause").hide(); 
    $("#play").show();
    }}
    
    </script>
    i wish this time the codes that i post make more sense and i wish i get this working cuz it took too long and still not :/


    Thanks in advance.

    Maxwel

  2. #17
    Join Date
    May 2014
    Posts
    900
    Ok, you have it inside myHandler instead of outside it. EVERY time you call 'myhandler' it's going to reset it. It needs to be independent of that parent function to work 'properly'... this also seems like a good candidate for an anonymous function to isolate the scope of this.

    Code:
    <script type="text/javascript"><!--
    
    (function(d) {
    
    	var
    		replay = d.getElementById('replay'),
    		container = d.getElementById('dl'),
    		myVideo = d.getElementById('myVideo'),
    		seconds = 10,
    		timer = false;
    		
    	function eventAdd(e, event, handler) {
    		if (e.addEventListener) e.addEventListener(event, handler, false);
    			else e.attachEvent('on' + event, handler);
    	}
    	
    	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 = false;
    	}
    	
    	eventAdd(myVideo, 'playing', function(e) {
    		$("#box").hide();  
    		$("#pause").show(); 
    		$("#clickhere").hide();
    		if (timer !== false) timer = window.setInterval(countdown, 1000);
    	});
    		
    })(document);
     
    --></script>
    Though still I really need to see the markup this is playing with to say more. I think a lot of the jQuery garbage you're doing here could be replaced with a single class swap and letting CSS do most of the heavy lifting on your player controls.
    Last edited by deathshadow; 08-11-2014 at 05:50 PM.
    Java is to JavaScript as Ham is to Hamburger.

  3. #18
    Join Date
    Aug 2014
    Posts
    13
    Hey bro,

    I really appreciate all u time and help but the code u provided me dont work. it dont even show the count down or the skip link.

    here is the code:

    Code:
    <script type="text/javascript">
    
    (function(d) {
    
    	var
    		replay = d.getElementById('replay'),
    		container = d.getElementById('dl'),
    		myVideo = d.getElementById('myVideo'),
    		seconds = 10,
    		timer = false;
    		
    	function eventAdd(e, event, handler) {
    		if (e.addEventListener) e.addEventListener(event, handler, false);
    			else e.attachEvent('on' + event, handler);
    	}
    	
    	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 = false;
    	}
    	
    	eventAdd(myVideo, 'playing', function(e) {
    		$("#box").hide();  
    		$("#pause").show(); 
    		$("#clickhere").hide();
    		if (timer !== false) timer = window.setInterval(countdown, 1000);
    	});
    		
    })(document);
     
    </script>

    I can't really pm u through webdeveloper.com so if u dont mind me sending to u whole code through an email u can send me ur email to my email "johnsilverix@gmail.com" and i will send u the whole code to urs .


    i have some questions if u don't u told me to stop using jquery so what i can use instead? also aint those <!-- --> are html commenting tags why u used them in above post?how we can check for "seconds--" if we are not decrementing the seconds before we check for it? can u explain for me these three parts "function eventAdd(e, event, handler), e.attachEvent('on' + event, handler); , function(d)" and why u used "d" in "function(d)" ?

    maybe these are dumb question but i try to learn more . also what are the strings that added in brackets that after any function? what are they useful for? cuz sometimes they are declared before the function and sometimes they are never declared and still i can see the pc get it.

    i wish i was clear in my questions and don't bother ya by asking them but i am really curious and want to know and learn. u can link me with tutorials if that can be easier for u to answer any of the questions above but please try to answer simple ones urself cuz i am sure it's gonna be easier and clear to understand.

    Thanks in advance

    Maxwel

  4. #19
    Join Date
    May 2014
    Posts
    900
    Quote Originally Posted by Maxwel View Post
    i have some questions if u don't u told me to stop using jquery so what i can use instead?
    Normal javascript without the bloated framework. Most of the time it's the same or less code on your part, and it's always less code overall.

    Quote Originally Posted by Maxwel View Post
    also aint those <!-- --> are html commenting tags why u used them in above post?
    So that browsers with scripting disabled, unavailable or unknown won't show the source code of the script in the middle of the page.
    http://www.w3.org/TR/html4/interact/....html#h-18.3.2

    They put a leading // when there's not a single JS engine in circulation that needs it as the HTML parser strips the --> long before it gets to the point of running scripting.

    Quote Originally Posted by Maxwel View Post
    how we can check for "seconds--" if we are not decrementing the seconds before we check for it?
    Much like in C, all operations will return their value for evaluation, even variable assignments.

    var a = 10;
    console.log(--a);
    console.log(a--);
    console.log(a);

    Will output 9, 9 and 8. Confused?

    --a performs the decrement BEFORE evaluating the value. 10-1 == 9, so it outputs 9. a-- performs the decrement AFTER evaluating the value. So it's 9, then it subtracts 1... making the last one output 8. Depending on the language or even the processor one or the other could be faster... (real fun).

    In this case "seconds--" evaluates the value, if it's zero that's treated as false. otherwise it's true... then it's decremented. On false we kill the timer so it doesn't go negative.

    so:
    Code:
    if (seconds--) {
      // do something
    }
    kind of the same as saying:

    Code:
    if (seconds) {
      seconds--;
      // do something
    } else seconds--;
    Though not exactly... that's a gross oversimplification.

    Quote Originally Posted by Maxwel View Post
    function eventAdd(e, event, handler), e.attachEvent('on' + event, handler);
    That's a polyfill -- it's just a simple helper function to make it so you can transparently add events in Modern Browsers, and IE. Everything except IE uses "addEventListener", which uses "attachEvent" instead. You have to remember that when Microsoft first implemented "JScript" it's called "JScript" and NOT "JavaScript" for a reason, they were worried about being sued by Nyetscape, so they created their own version with enough 'differences' to sqeak through. Honestly it's a miracle ANY scripting in IE is compatible with "rest of world".

    In either case those methods mean that if other scripts want to attach their own events, they won't conflict with each-other like using Element.onevent would -- or worse the stupid malfing onevent HTML attributes that IMHO should be removed from the HTML specification.

    Quote Originally Posted by Maxwel View Post
    function(d)" and why u used "d" in "function(d)" ?
    That's an anonymous function -- a function with no name that in this case is self instancing.

    A simple example:

    Code:
    (function(a) {
      alert(a);
    })('test');
    Would alert 'test'. NONE of the values inside that function exist in the global scope, meaning there's little to no risk of variables or functions inside it accidentally conflicting with other scripts.

    There's some noodle-doodle BS circulating about anonymous functions on how they've got this "massive" memory overhead -- they only do so if you are going to call it more than once as every time you pass an anonymous function by reference you're making a new copy. For example:

    Code:
    for (t = 0; t < labels.length; t++) {
      eventAdd(labels[t], 'click', function(e) { alert(e); });
    }
    Would create a separate function for each of those labels -- which IS a waste of memory. In that scenario you are better off doing:

    Code:
    function clickLabel(e) { alert(e); }
    
    for (t = 0; t < labels.length; t++) {
      eventAdd(labels[t], 'click', clickLabel });
    }
    Which would lower the memory footprint of the program.

    But if the function is only ever going to exist once, there's NO legitimate reason not to use them, particularly as 'scope isolators' / namespaces. It's one of those cases where people turn one little tiny corner-case where it's a problem into ignorant "NEVER USE IT" nonsense. Same as the people who say "never use tables" or "always use STRONG and EM instead of B and I" -- which is also a bunch of halfwit nonsense spouted by people who don't know enough on the topic to be flapping their gums.

    In any case, look at the opening and closing of that anonymous function (which is behaving as what PHP folks would call a singleton).

    Code:
    function(d) {
    })(document);
    So basically d == document. So we can say d.getElementsById instead of document.getElementsById. It's a petty way to save a few bytes, but it also creates a 'local scope' reference to document that thanks to how variables are looked up by most JavaScript engines, means it's able to be found faster.

    Picked up that trick from some of Google's code embeds for things like G+ likes. Good enough for Google it can't be that bad.

    Quote Originally Posted by Maxwel View Post
    also what are the strings that added in brackets that after any function? what are they useful for? cuz sometimes they are declared before the function and sometimes they are never declared and still i can see the pc get it.
    Not sure what you mean by that. Could you elaborate what you're referring to there?
    Last edited by deathshadow; 08-12-2014 at 04:30 AM.
    Java is to JavaScript as Ham is to Hamburger.

  5. #20
    Join Date
    Aug 2014
    Posts
    13
    nvm about the last question cuz u already answered it in ur previous answer. Also, i am sooo happy cuz today i learnt much about js from u and things began to get more easier and clear for me . appreciate it so much and really happy and through this topic and reading ur posts i learnt much in how i write better code and clean and how to save memo plus clarification of things i wanted to know much about js so thanks alot

    Also, i sent to ya the whole file to ur email and waiting ur reply whenever u can

    Yours,
    Maxwel

  6. #21
    Join Date
    May 2014
    Posts
    900
    Well, looking at the full thing, I'm ending up with more questions than answers -- like why are you forcing their second and third visits to the page to auto-refresh via HTTP with 0 waits? That's a unnecessary strain on the server for ... well, I've no clue why. I'm really not grasping what it is you are doing with counting the visits by IP, all you seem to have is broken annoying refreshes for christmas only knows what.

    Next you've got a section doing browser sniffing to serve two different copies of what SEEMS to be the same page... Browser sniffing is ALWAYS a steaming pile of /FAIL/ so I'd swing an axe at that as there's NO legitimate reason to be doing that... which would reduce the size of your php 60% or so.

    A big "problem" that's making it hard to work with is that you've just got too much stuff in the markup that should be in external files -- like the CSS and Scripting. Get those into external files so they can be cached, so PHP doesn't have to work as hard parsing all that output, and so it's easier to edit as you have them all in nice neat separate locations.

    The markup itself is... ouch. You've got a slew of tags and attributes like CENTER, FONT, BGCOLOR and so forth that have no business on any website written after 1998. You've got a H3 when you don't even have H1 or H2 before it so the heading orders are structural gibberish, you seem to be building massive strings for some sort of random output when the only difference betwixt them would be the value in the FILE attribute and SOURCE tags... etc, etc...

    Much less it's using the outdated/outmoded mysql_ functions, something that really was supposed to go the way of the dodo eight years ago, and that they finally added giant red warning boxes to the manual waving people off from using as they're going away soon.

    I'll ... dig deeper to see if I can make sense of what you're trying to accomplish... I think the first step is going to be dragging the markup into the light and swinging an axe at most of your PHP that isn't actually doing anything that should be done.
    Java is to JavaScript as Ham is to Hamburger.

  7. #22
    Join Date
    May 2014
    Posts
    900
    OH, you're also declaring BOTH UTF-8 by the HTML 5 way, and ISO-8859-1 via the META way... PICK ONE, not both.
    Java is to JavaScript as Ham is to Hamburger.

  8. #23
    Join Date
    Aug 2014
    Posts
    13
    hey again,

    firstly, i would like to thanks u for helping me and answering my questions and apologize for how messy is my code but i try to learn every day how to code a neat and well coded php/js codes .

    secondly, i actually refresh the page in the 2nd/3rd visit after i set their count number to 0 to make sure they dont directed to the link before they watch the ads vid. i know it dont make much sense but i am not sure why i did it that way much. i feel dumb :S

    secondly, i have read latest post and that made me want ask few question if u dont mind:

    1- what is the difference between UTF-8 by the HTML 5 way, and ISO-8859-1 via the META way?

    2- what i can do instead of checking browser type then display code that suits it tho?

    3- do u want me to use css instead of attributes like CENTER, FONT, BGCOLOR, etc?

    4- I never knew mysql_ functions that i use are outdated/outmoded, so where i can find new funcs?

    Thanks alot for everything and apologizes for asking too much

    Yours,
    Maxwel

  9. #24
    Join Date
    Aug 2014
    Posts
    13
    Hey again,

    sorry for posting another post but i can find the edit button and i was wondering if it is possible to detect each computer behind same ip? like how i can differentiate between a pc and another behind same ip? is there a way to get port number or some local ip to achieve that task?

    also i have another question is that i realized that this forum keep me logged even if my router restarted and my ip changed how is that accomplished as well

    Thanks again so so much.

    Yours,
    Maxwel

  10. #25
    Join Date
    May 2014
    Posts
    900
    Quote Originally Posted by Maxwel View Post
    secondly, i actually refresh the page in the 2nd/3rd visit after i set their count number to 0 to make sure they dont directed to the link before they watch the ads vid. i know it dont make much sense but i am not sure why i did it that way much. i feel dumb :S
    Still not following you on that...

    Quote Originally Posted by Maxwel View Post
    1- what is the difference between UTF-8 by the HTML 5 way, and ISO-8859-1 via the META way?
    They both do the same thing, declare the character set of the document -- the problem is they are two different values for the same information; that's like saying the language is English and then saying it's Portuguese -- which is it? NOT that it really matters as the mime-type sent by the server trumps those values, but it's still confusing to have both the new and old declarations declaring different values for the same field.

    Quote Originally Posted by Maxwel View Post
    2- what i can do instead of checking browser type then display code that suits it tho?
    Use code that works in all of them... I'm not even sure what 'difference' you'd have that warrants wasting that much code on browser sniffing as I'm not even seeing anything different enough in the markup between your two 'versions' to warrant it.

    Though if you had a well formed HTML to begin with...

    Quote Originally Posted by Maxwel View Post
    3- do u want me to use css instead of attributes like CENTER, FONT, BGCOLOR, etc?
    Pretty much, and that CSS belongs in an external stylesheet, NOT in the markup. HTML is for saying what things ARE, NOT what they look like. As such, those vendor specific tags that were added during the browser wars over a decade and a half ago have no business in the HTML; and to be brutally frank, they NEVER did!

    Quote Originally Posted by Maxwel View Post
    4- I never knew mysql_ functions that i use are outdated/outmoded, so where i can find new funcs?
    I would suggest that you use PDO. It's not that different even though it's object driven, and lets you use multiple SQL engines and not just mySQL. (though you can still use it if desired).
    http://php.net/manual/en/book.pdo.php

    The big thing there is "prepared queries" which auto-sanitizes values (no more escapestring nonsense), can be re-used with different data, and a whole host of other advantages. The other alternative is mysqli -- which I dislike for a variety of reasons.

    For example where in your code you have:
    Code:
    mysql_connect("", "", "") or die(mysql_error());
    mysql_select_db("") or die(mysql_error());
    
    $result = mysql_query("SELECT * FROM name WHERE ip = '$client_ip'") 
    or die(mysql_error());  
    
    $row = mysql_fetch_array($result);
    troublesome since it has no query failure handling...

    If I wrote that as PDO it would go:
    Code:
    $db = new PDO(
    	'mysql:host=localhost;dbname=database',
    	'username',
    	'password'
    );
    
    $statement = $db->prepare('
    	SELECT *
    	FROM name
    	WHERE ip = :ip
    ');
    
    $statement->execute([':ip' => $client_ip]);
    
    if ($row = $statement->fetch('PDO::FETCH_ASSOC')) {
    the first string passed to 'new PDO' is called a "data source name" or "PDN" for short. The first word before the colon says which database engine to use, the host says what host to use (like 127.0.0.1 or localhost), dbname is the database you are connecting to, so whatever you put as the = is equivalent to mysql_db_select's value.

    The PDO:repare method returns a PDOStatement on which you can pass values in an array with the PDOStatement::execute method. Putting a : before a name creates the identifier to match in the array.

    Not too tough.

    Quote Originally Posted by Maxwel View Post
    i was wondering if it is possible to detect each computer behind same ip? like how i can differentiate between a pc and another behind same ip? is there a way to get port number or some local ip to achieve that task?
    That question makes me almost understand what you were doing with the IP and the database and so forth, and why it made NO sense to me whatsoever. You're unaware of what "sessions" are.

    Forums and the like use SESSIONS, a method of storing data server-side based on a single cookie. A unique cookie typically called PHPSESSID is created and sent ot the browser, which in return passes it back with every file request. That ID is then used to pull information from a database automatically. you can store all sorts of information in the session -- like the user's database ID and it is kept server-side for the length of the 'session' while never sending that information client-side.

    You start a session with:

    session_start();

    at the start of any user-callable file you want to use sessions in. It will either continue the existing session, or create one if none exists. I usually suggest you then immediately call:

    session_regenerate_id();

    Which will create a new random session ID. Doing this takes a bit of extra overhead, but reduces the odds of what's called a "main in the middle" attack where someone takes that same cookie value and tries to fake it.

    You can then test if a value exists in the session and what it's value is:

    Code:
    if (
    	isset($_SESSION['test']) &&
    	($_SESSION['test'] == 1)
    ) {
    Or you could set it's value thus:

    $_SESSION['test'] = true;

    Because they're cookie driven, the IP address doesn't even play into it. That's how 99.99% of forums, blogs or other sites that have logins... handle tracking if a user is logged in.

    Though I like to store and compare the UA string and IP address in the session for comparison, and rejecting the session if those change as another way of fighting 'man in the middle' attacks. Mind you those are just as easy to fake, but it's like door-locks on a car -- it keeps the 'honest' people out.

    The nice part about PHP sessions is they take the 'grunt work' out of calling the database if all you are doing is tracking a visitor for the time of their visit when there's no corresponding login system or login required.
    Last edited by deathshadow; 08-14-2014 at 08:20 AM.
    Java is to JavaScript as Ham is to Hamburger.

  11. #26
    Join Date
    Aug 2014
    Posts
    13
    hey again, Thanks for the million time for answering my questions and i really appreciate it and sorry for late/delay reply but i couldnt get on pc for rl situations.

    1- I know about sessions but i never knew it can work without login system?! how is that done even tho?

    2- i didn't get about that part much "I like to store and compare the UA string and IP address in the session for comparison, and rejecting the session if those change as another way of fighting 'man in the middle' attacks". so can u explain it more detailed and easy way cuz it seems so important to help in preventing hacking ur login systems. hence, the website so will be great of u to explain it please for me deeper but easier

    3- any news about my script? did u get the point out of it yet? how how i can make that count down work without beginning from first every time user pause then play the video?


    Thanks for everything once again and sorry if i cause any disturbance or inconvenience by asking those questions but i really try to learn and hopefully when others who search for something u mentioned before they get things more clear and helpful as well

    Yours,

    Maxwel

  12. #27
    Join Date
    Aug 2014
    Posts
    13
    i don't know why my posts dont show anymore? is there any issues with them?

    Thanks in advance

    Maxwel

    - reply -> As a "newbie" all your posts are moderated, so there may be a delay before they become visible on the site. If a post is trivial it may be deleted, so not become visible at all. If a moderator has more concerns with your posts, they will generally contact you.

    jedaisoul.
    Last edited by jedaisoul; 09-01-2014 at 02:55 PM.

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