setinterval - Javascript wait until last event fired in callback before proceeding -


this pretty basic javascript question though involves chrome extension api.

chrome.tabs.onupdated.addlistener(function(tabid, changeinfo, tab) {     if (changeinfo.status == 'complete') {         //complete may fire multiple times per page update         var timer = 0, interval;         console.log(changeinfo.status);         clearinterval(interval);         interval = setinterval(function() {             if (timer == 5) {                 console.log('here');                 clearinterval(interval);             }             timer++;         }, 1000);     } }); 

i think script right delay everything. want every time 'complete' status happens, want check 5 seconds go , log 'here'. if 'complete' fires, want rid of previous timer , start new one. wait until 'complete's fired...i need fixing interval logic...

you have declare timer, , interval outside function scope, or it'll declare new 1 in scope, , clearinterval can't clear previous interval callback.

edit: stdob--, changed variable outside stick eventtarget, no need declare variables before register event anymore.

chrome.tabs.onupdated.addlistener(function(tabid, changeinfo, tab) {     if (changeinfo.status == 'complete') {         //complete may fire multiple times per page update         console.log(changeinfo.status);         // clear prev counter, if exist.         if (this.interval != null) {             clearinterval(this.interval);         }         // init timer         this.timer = 0;                         this.interval = setinterval(function() {             if (this.timer == 5) {                 console.log('here');                 clearinterval(this.interval);                 this.interval = null;             }             this.timer++;         }.bind(this), 1000);  // important .bind(this) context remain consistent.     } }); 

so every interval , timer points same target.

or if doesn't care happens in every second, why not use settimeout:

chrome.tabs.onupdated.addlistener(function(tabid, changeinfo, tab) {     if (changeinfo.status == 'complete') {         console.log(changeinfo.status);         if (this.timeout != null) {             cleartimeout(this.timeout);         }          this.timeout = settimeout(function() {             console.log("here");             this.timeout = null;         }.bind(this), 5000);     } }); 

Comments

Popular posts from this blog

c# - Better 64-bit byte array hash -

webrtc - Which ICE candidate am I using and why? -

php - Zend Framework / Skeleton-Application / Composer install issue -