javascriptperformancejquery-eventsjquery-on

I have 2 bind functions and when I run them, it's very slow


I'm new at writing Javascript and jQuery. If I have two slider and they will effect each other when I move each one it's very slow I use 2 bind command on each slider

Is the bind command will have slow performance?

Here is my code:

<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.min.css" />
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>  
<script src="http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.min.js"></script> 
<script>
$(document).ready(function(e) {
    init();
});

function init() {
    $("#f").bind('change', a);
    $("#g").bind('change', b);
}

function a() {
    var x;
    var y;
    y = $("#f").val();
    x = ftoc(y);
    $('#g').val(x);
    $('#g').slider('refresh');
}

function ftoc(y) {
    var z;
    z = (y - 32) * 5 / 9;
    return z;
}

function b() {
    var x1;
    var y1;
    y1 = $("#g").val();
    x1 = ftoc1(y1);
    $('#f').val(x1);
    $('#f').slider('refresh');
}

function ftoc1(y1) {
    var z1;
    z1 = y1 * (9 / 5) + 32;
    return z1;
}
</script>

</head>

<body>
<div data-role="page" id="page">
<div data-role="header">
<h1>Header</h1>

</div>

<div data-role="content">

<div data-role="fieldcontain">
<label for="slider">Fah</label>
<input type="range" name="slider" data-track-theme="b" id="f" value="0" min="-50" max="200" />

<label for="slider">Celsius</label>
<input type="range" name="slider" data-highlight="true" id="g" value="0" min="-50" max="150" />

</div>


</div>
</div>

</body>
</html>

Solution

  • You can disable the bind when coming programmatically

    function init() {
        $("#f").bind('change', a);
        $("#g").bind('change', b);
    }
    
    var isChanging = false;
    
    function a() {
        if(isChanging)return;
        isChanging = true;
        var x;
        var y;
        y = $("#f").val();
        x = ftoc(y);
        $('#g').val(x);
        $('#g').slider('refresh');
        isChanging = false;
    }
    
    function ftoc(y) {
        var z;
        z = (y - 32) * 5 / 9;
        return z;
    }
    
    function b() {
        if(isChanging)return;
        isChanging = true;
    
        var x1;
        var y1;
        y1 = $("#g").val();
        x1 = ftoc1(y1);
        $('#f').val(x1);
        $('#f').slider('refresh');
        isChanging = false;
    }
    
    function ftoc1(y1) {
        var z1;
        z1 = y1 * (9 / 5) + 32;
        return z1;
    }
    

    the recursion created makes the change slow... see the fiddle a solution -> http://jsfiddle.net/Castrolol/hQ5jz/