简体   繁体   中英

Change value of a variable inside a timer event Javascript

I am increasing value of a variable inside a timer.It is also inside a button onClick event.

setInterval(function () {
    document.getElementById('z_in').addEventListener('click', function () {
        zoom_level = 1;
    }, false);
    document.getElementById('z_out').addEventListener('click', function () {
        zoom_level = 3;
    }, false);
    document.getElementById('rotate').addEventListener('click', function () {
        angle = angle + 10;

    }, false);
    Find(db, minLon, maxLon, minLat, maxLat, zoom_level, angle, stage, layer, i);
    i++;
    //angle = 0;
    console.log();
}, 1000);

Here angle increases too much not ten by ten in every loop.What is the reason of this problem?

If you need listeners only when timer is active, you can use something like this:

var timer, i = 0, zoom_level = 1, angle = 0;
var z_in_el = document.getElementById('z_in');
var z_out_el = document.getElementById('z_out');
var rotate_el = document.getElementById('rotate');

function zoomIn(){
    zoom_level = 1;
}
function zoomOut(){
    zoom_level = 3;
}
function rotate(){
    angle += 10;
}

function startTimer(){
    addListeners();
    timer = window.setInterval(function(){
        i++;
        Find(db, minLon, maxLon, minLat, maxLat, zoom_level, angle, stage, layer, i);
        console.log(i, zoom_level, angle);
    }, 1000); 
}

function stopTimer(){
    removeListeners();
    window.clearInterval(timer);
}

function addListeners(){
    z_in_el.addEventListener("click", zoomIn, false);
    z_out_el.addEventListener("click", zoomOut, false);
    rotate_el.addEventListener("click", rotate, false);
}

function removeListeners(){
    z_in_el.removeEventListener("click", zoomIn, false);
    z_out_el.removeEventListener("click", zoomOut, false);
    rotate_el.removeEventListener("click", rotate, false);
}

Use startTimer() to set interval or stopTimer() to remove it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM