javascriptsetinterval

How to change interval time under a condition in JavaScript?


I need a function that will print letters one by one but make pauses after ",". I tried to do it like this but it didn't work :

var span = document.getElementById('text')
function print(string){
  var i = 0
  var time = 50
  var timer = setInterval(function(){
    span.innerHTML += string[i++]
    if(string[i] == ","){
      time = 150
    }else{
      time = 50
    }  
  },time)
}

Solution

  • I am not sure you can change the time of setTimeinterval once defined. It is better to use a setTimeout. I'm using recursive function to achieve the desired -

    function print(string, i){
      var time = 50
      if(string[i]==",") time = 1000
      setTimeout(function(){
        span.innerHTML += string[i]
        if(i<string.length-1) print(string,++i)
      },time)
    
    }
    

    complete example can be found here