Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Incrementing a local variable using JavaScript

I am trying to increment a counter, but I would like to move the variable out of the global namespace and declare it locally. I'm not sure how to do this. Thanks for your help.

This is the code I'm using at the moment.

var mediaClickCounter = 0;
function refreshMediaAds() {
    if (mediaClickCounter < 2) {
        mediaClickCounter++;
    } else {
        mediaClickCounter = 0;
        refreshAds();
    }
}
like image 527
user699242 Avatar asked Apr 21 '26 11:04

user699242


2 Answers

// the function creates a local scope. 
var refreshMediaAds = (function() { 
    var mediaClickCounter = 0;
    // once executed it returns your actual function.
    return function _refreshMediaAds() {
        if (mediaClickCounter < 2) {
            mediaClickCounter++;
        } else {
            mediaClickCounter = 0;
            refreshAds();
        }
    }
// you execute the function.
})();

Closures <3.

like image 140
Raynos Avatar answered Apr 23 '26 00:04

Raynos


how about using something like this:

var ClickCounter = {
 mediaClickCounter: 0,

 refreshMediaAds:function() {
    if (this.mediaClickCounter < 2) {
        this.mediaClickCounter++;
    } else {
        this.mediaClickCounter = 0;
        refreshAds();
    }
 }
};

and then you can just use ClickCounter.refreshMediaAds() which will increment the member variable.

like image 20
Liv Avatar answered Apr 23 '26 01:04

Liv